Django-使用子对象过滤查询集(ForeignKey) [英] Django - Filter queryset with child objects (ForeignKey)
本文介绍了Django-使用子对象过滤查询集(ForeignKey)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个模型,其中2个对应第一个。
I have 3 Models, and 2 of them correspond to the first one.
class Parent(models.Model):
name = models.CharField....
...
class Child1(models.Model):
parent = models.ForeignKey(Parent)
...
class Child2(models.Model):
parent = models.ForeignKey(Parent)
...
现在,在我看来,我有2个查询集,分别过滤为 Child1
和 Child2
对象。
Now, in my view I have 2 querysets filtered of Child1
and Child2
objects.
是否可以检索所有父项
对象,
Is there a way to retrieve all the Parent
objects that are in the filtered querysets?
类似...
children1 = Child1.objects.filter(blah=blah)
children2 = Child2.objects.filter(blah=blah)
parents = Parent.objects.filter(self__in=children1 or self__in=children2)
注意上面的代码根本不起作用,仅是个主意。
NOTE The code above does not works at all, it is just the idea.
推荐答案
是:
from django.db.models import Q
children1 = Child1.objects.filter(blah=blah)
children2 = Child2.objects.filter(blah=blah)
parents = Parent.objects.filter(Q(child1__in=children1) | Q(child2__in=children2))
查看文档:
- https:// docs .djangoproject.com / en / 1.7 / ref / models / querysets /#in
- https://docs.djangoproject.com/en/1.7/topics/db/queries/#lookups-that-span-relationships
- https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q-objects
- https://docs.djangoproject.com/en/1.7/ref/models/querysets/#in
- https://docs.djangoproject.com/en/1.7/topics/db/queries/#lookups-that-span-relationships
- https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q-objects
这篇关于Django-使用子对象过滤查询集(ForeignKey)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文