Pattu
Pattu

Reputation: 3809

Django select_related filter

I have the following Django models.

class A(models.Model):
    tmp = models.ForeignKey(B)
    active = models.BooleanField()

class B(models.Model):
    active = models.BooleanField()
    archived = models.BooleanField()

Now I have the following query.

A.objects.select_related(B).filter(active=True)

Now this fetches all the objects of B. Now how can I include a filter of active=True and archived=False in the select_related clause for model B.

Upvotes: 24

Views: 34023

Answers (1)

Sayse
Sayse

Reputation: 43300

The same as you would with any other related field, with a __ lookup..

A.objects.select_related(B).filter(active=True, tmp__active=True, tmp__archived=False)

Using select related doesn't change anything here, its purpose is about what information is returned with the results, it has no effect on filtering at all.

Upvotes: 39

Related Questions