Shift 'n Tab
Shift 'n Tab

Reputation: 9443

Get object IN a model with particular field value OR NOT IN a related model

am new to django so complex querying is becoming difficult.

I have a model Animal and Heat i would like to fetch an Animal instance with farm=1 AND sex='female' AND an Animal instance with Heat.is_active=True AND Heat.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

Answers (1)

Evans Murithi
Evans Murithi

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

Related Questions