python - 在 Django ORM 中获取相关模型计数的有效方法

标签 python django postgresql orm

我正在研究 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 ...

现在,我需要显示一个包含客户 的表格,并显示每个客户创建的订单数量。

直接的代码是:

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.

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

最佳答案

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

query = Customer.objects.select_related('user').annotate(
    orders_count=Count('<b>user__created_orders</b>')
)

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

关于python - 在 Django ORM 中获取相关模型计数的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58268363/

相关文章:

python - 时间数据 'June 13, 1980 (United States)' 与格式 '%m/%d/%Y'(匹配)不匹配

python - Python模块单元测试的最佳文件结构组织?

django - 在 Django Rest Framework 中,如何限制序列化的外键对象数量

mysql - 生产中的 heroku rails 3 代码错误

ruby-on-rails-3 - 如何在 PostgreSQL 中 GROUP BY 几天?

sql - PostgreSQL:授予用户对 PostgreSQL 数据库的所有权限

python - Flask-restplus - 模型继承和 json 字段顺序

python - 使用 google oauth 和标志 --noauth_local_webserver 时出现重定向错误

python - 尝试更新单个 Django 表单/模型字段失败,因为未提供用户 ID(外键)

Django 查询是否可以使用 self