问题
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)
...
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?
Something like...
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.
回答1:
Yes:
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))
see docs:
- 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://stackoverflow.com/questions/28417613/django-filter-queryset-with-child-objects-foreignkey