Filter through a related django model

How can I generate a query_set through a linked model?

For example, how can I do this:

UserProfile.objects.filter(user.is_active=True) # Can't use user.is_active to filter 

A trivial question, a trivial answer. But I will keep it here for posterity.

+6
source share
3 answers
 UserProfile.objects.filter(user__is_active=True) 

This is well documented in Django docs.

+8
source

From a Django Document

Django offers a powerful and intuitive way to "keep track" of relationships in a search, taking care of SQL JOINs for you automatically, behind the scenes. To encompass relationships, simply use the field name of related fields in different models, separated by double underscores, until you get to the field you want.

In your example, this would be:

  UserProfile.objects.filter(user__is_active=True) 
+3
source

The easiest way to track relationships is to use a simple "__".

UserProfile.objects.filter (user__is_active = True)

They can also be changed together (i.e. user_parent_email = ' abc@def.com )

+2
source

Source: https://habr.com/ru/post/896822/


All Articles