如何在 django orm 中聚合嵌套的多对多关系

问题描述 投票:0回答:1

给出伪定义:

class User:
    name: string
    
class Account:
    owner: foreignkey(User, related_name="accounts")

class Transactions:
    type: Enum(1,2,3)
    account: foreignkey(Account, related_name="transactions"
    value: Int

如何使用 django ORM 编写此查询?

SELECT user.id, type, AVG(value) as type_average
FROM user
JOIN account ON account.owner = user.id
JOIN transactions ON transactions.account = account.id
GROUP BY user.id, type
django django-models
1个回答
0
投票

.annotate(…)
 [Django-doc]:

from django.db.models import Avg, F

User.objects.values(
    user_id=F('pk'), type=F('accounts__transactions__type')
).annotate(type_average=Avg('accounts__transactions__value')).order_by(
    'user_id', 'type'
)
© www.soinside.com 2019 - 2024. All rights reserved.