【问题标题】:Filter through a related model django通过相关模型过滤 django
【发布时间】:2011-09-07 19:35:29
【问题描述】:

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

例如,我该怎么做:

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

琐碎的问题,琐碎的答案。但为了后代,我会把它留在这里。

【问题讨论】:

  • 我很高兴你做到了!这些天阅读文档的人,更容易来 SO!

标签: django django-queryset


【解决方案1】:
UserProfile.objects.filter(user__is_active=True) 

这很好 documented 在 Django 文档中。

【讨论】:

【解决方案2】:

来自Django documention

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

在您的示例中,这将是:

 UserProfile.objects.filter(user__is_active=True)

【讨论】:

    【解决方案3】:

    了解关系的最简单方法是使用简单的“__”。

    UserProfile.objects.filter(user__is_active=True)

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

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 2020-01-19
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多