1
我有兩個模型的所有對象:獲取與空集相關的那些
class Content(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = generic.GenericForeignKey()
show = models.BooleanField(default=False)
class Foo(models.Model):
rel = generic.GenericRelation(Content)
,我想所有的Foo方法這是相關內容的對象(將只有一個)有show==True
,或者沒有按根本沒有相關的對象。就像:
Foo.objects.filter(Q(rel__show=True) | Q(rel__hasnone=True))
但當然在django中沒有什麼像hasnone
。
是否有任何其他方式可以完成該操作(不幸的是,聚合不適用於泛型關係,而且我無法計數項目)。
我在下面看到了你的答案,但這裏有一個更簡單的想法:循環遍歷相關集合並將具有相關記錄的所有對象附加到列表中。然後,再次遍歷模型,並跳過列表中的所有記錄。 這會慢一些,但有利於完全使用python和Django ORM。 – 2014-11-08 16:37:46