Django查询表查找仅存在于父字段

时间:2017-11-16 12:23:44

标签: python django django-models

我一直在努力做一个查询,以获取Item仅在Parnet字段而不是Child字段中存在的行。

这是模特。

class Item(models.Model):
    text = models.CharField()

class ItemRelations(models.Model):
    child = models.ForeignKey('Item', related_name='itemchild')
    parent = models.ForeignKey('Item', related_name='itemparent')

所以我只想过滤掉不是孩子的物品,而是父物品。我称之为firstParent。

我尝试了很多不同的方法。我想完成这样的事情。

firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self)

有可能吗?或者是否必须进行多个查询和循环来管理它?

2 个答案:

答案 0 :(得分:2)

我建议使用isnull filter for readability.

firstParent = Item.objects.filter(itemparent=self, itemchild__isnull=True)

在此评论中给出的具体示例中,Item.pkItem类的属性。您想要项目实例,而不是类。

我相信,重新阅读,问题是:

显示Item为父项但不是子项的项。在那种情况下:

firstParent = Item.objects.filter(itemparent__isnull=False, itemchild__isnull=True)将为您提供与之匹配的对象的查询集。

您可以随后希望进一步过滤以匹配其他方面。请记住django querysets are lazy。不要混淆使多个过滤器与实际查询/数据库命中混淆。

  

QuerySets很懒 - 创建QuerySet的行为不涉及任何数据库活动。您可以整天将过滤器堆叠在一起,在评估QuerySet之前,Django实际上不会运行查询。

答案 1 :(得分:0)

有可能。

firstParent = Item.objects.exclude(child=self).filter(parent=self)

在过滤前写入排除。