Reputation: 9443
am new to django so complex querying is becoming difficult.
I have a model
Animal
andHeat
i would like to fetch an Animal instance withfarm=1
ANDsex='female'
AND an Animal instance withHeat.is_active=True
ANDHeat.is_bred=False
Here is my models.
class Animal(models.Model):
farm = models.ForeignKey(Farm, related_name='farm_animals', on_delete=models.CASCADE)
name = models.CharField(max_length=25)
sex = models.CharField(max_length=7)
class Heat(models.Model):
animal = models.ForeignKey(Animal, related_name='heats', on_delete=models.CASCADE)
is_bred = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
So far i tried this query:
Animal.objects.filter(
farm=1, sex='female',
heats__is_active=True,
heats__is_bred=False
)
I can fetch a data if an animal instance HAS HEAT RECORD however i can't fetch any when there is NO HEAT RECORD.
Upvotes: 0
Views: 34
Reputation: 3257
You can use OR between the two pairs of conditions using the Q()
object:
from django.db.models import Q
Animal.objects.filter(
(Q(farm=1) & Q(sex='female')) |
(Q(heats__is_active=True) & Q(heats__is_bred=False))
)
This will give you a queryset containing animals that don't even have a Heat
record.
Upvotes: 2