Filter through a related model django

2019-02-17 06:34发布

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.

3条回答
地球回转人心会变
2楼-- · 2019-02-17 06:53
UserProfile.objects.filter(user__is_active=True) 

This is well documented in the Django docs.

查看更多
仙女界的扛把子
3楼-- · 2019-02-17 07:08

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='abc@def.com')

查看更多
叼着烟拽天下
4楼-- · 2019-02-17 07:09

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)
查看更多
登录 后发表回答