通过相关模型django过滤

时间:2022-09-02 20:16:54

How can I generate a query_set through a related model?

如何通过相关模型生成query_set?

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 个解决方案

#1


8  

UserProfile.objects.filter(user__is_active=True) 

This is well documented in the Django docs.

这在Django文档中有详细记载。

#2


3  

From the Django documention

来自Django的文档

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.

Django提供了一种强大而直观的方式来“跟踪”查找中的关系,在后台自动处理SQL JOIN。要跨越关系,只需使用跨模型的相关字段的字段名称,用双下划线分隔,直到到达所需的字段。

In your example this would be:

在您的示例中,这将是:

 UserProfile.objects.filter(user__is_active=True)

#3


2  

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')

这些也可以一起改变(即user_parent_email='abc@def.com')

#1


8  

UserProfile.objects.filter(user__is_active=True) 

This is well documented in the Django docs.

这在Django文档中有详细记载。

#2


3  

From the Django documention

来自Django的文档

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.

Django提供了一种强大而直观的方式来“跟踪”查找中的关系,在后台自动处理SQL JOIN。要跨越关系,只需使用跨模型的相关字段的字段名称,用双下划线分隔,直到到达所需的字段。

In your example this would be:

在您的示例中,这将是:

 UserProfile.objects.filter(user__is_active=True)

#3


2  

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')

这些也可以一起改变(即user_parent_email='abc@def.com')