我使用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)
答案 0 :(得分:0)
如django docs中所述,仅允许count(),order_by(),values(),values_list()和联合查询集切片。您无法根据联合查询集进行过滤。
这意味着,您必须先对查询应用过滤器,然后再对它们应用联合。