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.
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:
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With