Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Filter queryset with child objects (ForeignKey)

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.

like image 264
Alex Lord Mordor Avatar asked Feb 10 '23 23:02

Alex Lord Mordor


2 Answers

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
like image 64
Anentropic Avatar answered Feb 13 '23 22:02

Anentropic


1- add a related_name to your child Models :

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- import 'Q lookups' inside your views module :

    from django.db.models import Q

3-then inside your view you can use filter as the following :

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

i hope this helpful for you .

like image 22
K.A Avatar answered Feb 13 '23 22:02

K.A