Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 822
Pattu Avatar asked Dec 02 '16 07:12

Pattu


People also ask

What is Select_related in Django?

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.

Why are QuerySets considered lazy?

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.

What's the difference between Select_related and Prefetch_related in Django ORM?

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.

What is Django filter?

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.


Video Answer


1 Answers

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.

like image 72
Sayse Avatar answered Oct 06 '22 09:10

Sayse