Django - 使用子对象过滤查询集(ForeignKey)

时间:2015-02-09 19:22:21

标签: django django-queryset

我有3个模型,其中2个对应第一个。

class Parent(models.Model):
    name = models.CharField....
    ...

class Child1(models.Model):
   parent = models.ForeignKey(Parent)
   ...

class Child2(models.Model):
   parent = models.ForeignKey(Parent)
   ...

现在,在我看来,我有2个Child1Child2个对象的查询集。

有没有办法检索过滤后的查询集中的所有Parent个对象?

像...一样的东西。

children1 = Child1.objects.filter(blah=blah)
children2 = Child2.objects.filter(blah=blah)
parents = Parent.objects.filter(self__in=children1 or self__in=children2)

注意上面的代码根本不起作用,这只是想法。

2 个答案:

答案 0 :(得分:3)

是:

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))

参见文档:

答案 1 :(得分:0)

1-将相关名称添加到您的朋友中:

class Parent(models.Model):
    name = models.CharField....
    ...

class Child1(models.Model):
   parent = models.ForeignKey(Parent, related_name='related_Child1')
   title1 =  models.CharField(max_length=30)
   ...

class Child2(models.Model):
   parent = models.ForeignKey(Parent, related_name='related_Child2')
   title2 =  models.CharField(max_length=30)

2-然后您可以在视图过滤器中使用它:

    from django.db.models import Q

    search_words = "test_word"
    chaild1_search = Child1.objects.filter(Q(title1__icontains=search_words))
    chaild2_search = Child2.objects.filter(Q(title2__icontains=search_words))

    queryset_list_parent = Parent.objects.filter(Q(related_Child1__in=chaild1_search )|
                                          Q(related_Child2__in=chaild2_search)
                                          ).distinct()