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

Django - Filter queryset with child objects (ForeignKey)

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

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

是:

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- 将 related_name 添加到您的 child 模型中:

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- 在视图模块中导入 'Q lookups' :

    from django.db.models import Q

3-然后在您的视图中,您可以使用如下过滤器:

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

希望对您有所帮助。