Django - Filter queryset with child objects (ForeignKey)

北慕城南 提交于 2019-12-22 10:02:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!