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
.
Using select_related() Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects.
This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.
select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.
Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.
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.
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