Django - queryset.union返回破坏的查询集:filter()和get()返回所有内容

时间:2018-06-01 07:42:31

标签: python django django-queryset

我使用queryset.union来连接两个性质相同的查询集,但在结果上使用.get().filter()并不能正常工作:

>>>foo = obj1.father.all()
>>>foo
<QuerySet [<Link: l1>, <Link: l2>]>
>>>foo.get(pk=0)
<Link: l1>
>>>bar = foo.union(obj2.father.all())
>>>bar
<QuerySet [<Link: l1>, <Link: l2>], <Link: l3>], <Link: l4>]>
>>>bar.filter(pk=0)
<QuerySet [<Link: l1>, <Link: l2>], <Link: l3>], <Link: l4>]>
>>>[l.pk for l in bar]
[0, 1, 2, 3]

我应该使用除.union()以外的其他东西来连接查询集吗?我该怎么办?

my models.py:

class Article(models.Model):
     name = models.CharField(max_length=255,
                        unique=True,
                        verbose_name = _("Name"),
                        help_text=_("Name of the article"))

class Link(models.Model):
    father = models.ForeignKey(Article, related_name="father", on_delete=models.CASCADE)
    child = models.ForeignKey(Article, related_name="child", on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:0)

django docs中所述,仅允许count(),order_by(),values(),values_list()和联合查询集切片。您无法根据联合查询集进行过滤。

这意味着,您必须先对查询应用过滤器,然后再对它们应用联合。