【问题标题】:Effecient way to fetch related models count in Django ORM在 Django ORM 中获取相关模型计数的有效方法
【发布时间】:2020-02-04 16:17:39
【问题描述】:

我正在开发 Django 1.10 和 PostgreSQL9.6

我的项目中有两个模型:订单和客户。我还使用 Django 的 auth.User 来存储登录凭据。

这是一段代码:

from django.contrib.auth.models import User
from django.db import models


class Order(models.Model):
    created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='created_orders')
    # ... other fields ...

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # ... other fields ...

现在,我需要显示一个customers 的表格,并显示他们每个人创建的一些订单。

直截了当的代码是:

for customer in Customer.objects.all():
    print(customer.user.created_orders.count())

现在我需要避免 N+1 问题并让 Django 以恒定数量的查询获取所有数据。

我试过写类似的东西:

    query = Customer.objects.select_related('user').annotate(
        orders_count=Count('user.created_orders')
    )

但这给了我一个像Cannot resolve keyword 'user.created_orders' into field.这样的错误

你能帮我解决这个问题吗?

【问题讨论】:

    标签: python django postgresql orm


    【解决方案1】:

    您应该在此处使用点 (.),而应使用两个连续的下划线 (__):

    query = Customer.objects.select_related('user').annotate(
        orders_count=Count('user__created_orders')
    )

    请注意,您确实不需要需要.select_related('user') 来注释查询集。但是,如果您打算稍后在逻辑中使用.user,它确实可以提高性能。

    【讨论】:

    • 我很接近这个,但在 select_related 中使用了 user__created_orders :D。谢谢你
    • @atomAltera:好吧,我确实认为这是某种“大脑冻结”,因为查询的其余部分确实非常接近:)。
    猜你喜欢
    • 2018-04-03
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2019-05-01
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多