我有以下模型(简化),其中警告模型是通用外键,可以包括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')
我想检索任何没有任何警告的场合,但也要排除警告表中状态='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)