【问题标题】:Django ORM querying nested modelsDjango ORM查询嵌套模型
【发布时间】:2020-09-04 08:03:00
【问题描述】:

我想使用 django ORM 来过滤 db 中的一些记录, 我有一个名为User 的模型,其中包含一个字段profile,这是另一个模型, 当我执行以下操作时,所有用户都拥有个人资料:

users = User.objects.filter(Q(profile__isnull=False))

profile 有一个字段age 我想删除所有个人资料和年龄>30 的用户。 所以我遍历了所有有个人资料的用户,然后检查他们的年龄是否 > 30。

for user in  users:
    if user.profile.age>30:
          user.delete()

有没有办法在查询中直接使用user.profile.age>30

【问题讨论】:

  • 试试:User.objects.filter(Q(profile__isnull=False) & Q(profile__age__gt=30))
  • 不客气。很高兴听到它奏效了。

标签: python django django-models django-orm


【解决方案1】:

我通过组合Django 中的Q 对象解决了这个问题,如下所示:

User.objects.filter(Q(profile__isnull=False) & Q(profile__age__gt=30))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2019-01-05
    • 2018-12-01
    • 2017-11-25
    相关资源
    最近更新 更多