Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter through a related model django

How can I generate a query_set through a related model?

For example, how can I do this:

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

Trivial question, trivial answer. But I'll keep it here for posterity's sake.

like image 435
Brian D Avatar asked Sep 07 '11 19:09

Brian D


3 Answers

From the Django documention

Django offers a powerful and intuitive way to "follow" relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across 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)
like image 32
Ulrich Dangel Avatar answered Nov 15 '22 08:11

Ulrich Dangel


UserProfile.objects.filter(user__is_active=True) 

This is well documented in the Django docs.

like image 165
S.Lott Avatar answered Nov 15 '22 08:11

S.Lott


The easiest way to follow a relationship is to use a simple "__".

UserProfile.objects.filter(user__is_active=True)

These can be changed together as well (ie user_parent_email='[email protected]')

like image 30
kkaehler Avatar answered Nov 15 '22 06:11

kkaehler