我有以下模型(简化),其中警告模型是通用外键,可以包括 Occasion 对象(但也包括其他类型)
Occasion(models.Model):
start_date = models.DateField()
Warnings(models.Model):
status = models.CharField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
我想检索任何没有任何警告的场合,但也排除任何在警告表中具有 status='new' 的场合。我应该如何编写这个查询?
编辑:这是得到正确结果的 SQL
select * from occasion left join warnings
on occasion.id = warnings.object_id
and warnings.content_type_id = 13 --type id for the model.
and warnings.status <> 'new';
再次编辑:
这就是我解决它的方法:
#First get any occasions with status='new' from warnings
ctype = ContentType.objects.get(app_name="myapp", model="ocassion")
warnings = warning.objects.filter(content_type=ctype, status='new')
#Filter out only object_ids
warning_occasion_list = set(list(warnings.values_list('object_id', flat=True))
#Then exclude these from the occasion query
occasions = occasion.objects.all().exclude(occasion_id__in=warning_occasion_list)