如何为数据表获取正确的查询集
How to get correct queryset for Datatable
我有两个模型,Profile 和 Payment。我需要在前端显示一个包含字段 "Username"、"Email" 和 "Total Spent" 的数据表。 Username 和 Email 可以在 Profile 模型中找到,所以查询集将是:
def get_initial_queryset(self):
return Profile.objects.all()
但是,"Total Spent" 信息需要计算为在相同 "profile_id" 的付款模型中找到的所有 "payment_amount" 字段的总和,因为用户可以有两个付款(一个数量为 5,另一个数量为 15,我需要显示 total_spent=20).
问题是,因为我使用的是数据表,所以我需要这个"total_spent"字段在查询集中 (使用注释或其他方法)。
我试过使用 Subquery 和 OuterRef,但在生成的最终 SQL 中出现错误。
return Profile.objects.all().annotate(
money_spent=Subquery(
Payment.objects.filter(user_id__in=OuterRef('id')).annotate(
money_spent=Sum('amount')
),
output_field=CharField()
)
)
但这给了我 SQL 错误:(1241, 'Operand should contain 1 column(s)')
如何获得正确的查询集?
Django 版本:1.11 |
Python版本:3.6.8
你根本不需要做子查询你可以在docs regarding joins and aggregates
中查看更多
Profile.objects.annotate(money_spent=Sum('payment__amount'))
这将导致以下结果
SELECT profile.*, SUM(payment.amount) AS money_spent
FROM profile
LEFT OUTER JOIN payment ON payment.profile_id = profile.id
GROUP BY profile.id
我有两个模型,Profile 和 Payment。我需要在前端显示一个包含字段 "Username"、"Email" 和 "Total Spent" 的数据表。 Username 和 Email 可以在 Profile 模型中找到,所以查询集将是:
def get_initial_queryset(self):
return Profile.objects.all()
但是,"Total Spent" 信息需要计算为在相同 "profile_id" 的付款模型中找到的所有 "payment_amount" 字段的总和,因为用户可以有两个付款(一个数量为 5,另一个数量为 15,我需要显示 total_spent=20).
问题是,因为我使用的是数据表,所以我需要这个"total_spent"字段在查询集中 (使用注释或其他方法)。
我试过使用 Subquery 和 OuterRef,但在生成的最终 SQL 中出现错误。
return Profile.objects.all().annotate(
money_spent=Subquery(
Payment.objects.filter(user_id__in=OuterRef('id')).annotate(
money_spent=Sum('amount')
),
output_field=CharField()
)
)
但这给了我 SQL 错误:(1241, 'Operand should contain 1 column(s)')
如何获得正确的查询集?
Django 版本:1.11 | Python版本:3.6.8
你根本不需要做子查询你可以在docs regarding joins and aggregates
中查看更多Profile.objects.annotate(money_spent=Sum('payment__amount'))
这将导致以下结果
SELECT profile.*, SUM(payment.amount) AS money_spent
FROM profile
LEFT OUTER JOIN payment ON payment.profile_id = profile.id
GROUP BY profile.id