Django:查询GenericRelation为null的情况
我想查询一个模型,找出那些通用关系字段不为空的实例(也就是说,在下面的例子中,我想找出 document.count() > 0 的实例):
class Report(models.Model):
document = generic.GenericRelation(Document)
类似这样的:
Report.objects.filter(date__gte=twomonths).exclude(document__isnull=True)
可惜这样做不行——查询返回了那些没有“document”的对象(也就是说,它返回了 document.count() 为 0 的对象)。
有没有办法查询那些通用关系为空的实例呢?
1 个回答
2
我觉得你的问题里可能还有一些矛盾。注意:“我在找 document.count() 等于 0 的情况”,然后又说,“不幸的是,这个方法不行——查询返回了没有 'document' 的对象(也就是说,它返回了 document.count() 为 0 的对象)”。
如果你想要那些没有任何文档的 Report
,你可以使用:
Report.objects.filter(document__isnull=True)
或者
Report.objects.exclude(document__isnull=False)
如果你想要那些至少有一个文档的 Report
,你可以使用:
Report.objects.filter(document__isnull=False)
或者
Report.objects.exclude(document__isnull=True)