如何获得QuerySet不dict django汇总
我正在使用此QuerySet作为我的要求,
invoices = Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True))
该要求返回dict --->
{'total_amount': Decimal('17700.00'), 'number_of_invoices': 2}
但是我想要QuerySet我该怎么做。 感谢您的帮助
i'm using this queryset for my requirements
invoices = Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True))
which returns dict--->
{'total_amount': Decimal('17700.00'), 'number_of_invoices': 2}
but I want queryset how can i do that..
Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是汇总的操作:)
您可以将
Decimalfield
添加到发票
模型,在每次保存之前汇总total_amount
。我建议这样做的信号。apps.py
Signals.py
您必须为
order
设置类似的信号,因此,如果您更改order
对象,相关Invoice
对象将是重新计算。之后,
querySet
将保持为querySet
,每个对象都将始终具有caclated字段。This is what aggregate do :)
You can add a
DecimalField
toInvoice
model, that aggregatestotal_amount
during before every save. I suggest signals for that.apps.py
signals.py
You have to set similar signals for your
Order
, so if you changeOrder
object, the relatedInvoice
object will be recalculated.After that
QuerySet
will stay asQuerySet
and every object will have always caclulated field.而不是使用
.Aggregate(...)
使用.annotate(...)
这将返回给定表达式的 querySet然后要获得
sum(...)< /code>
&amp;
count(...)
field of this发票[0] .total_amount__sum
&amp;发票[0] .number_of_invoices__count
Instead of using
.aggregate(...)
use.annotate(...)
this will return a QuerySet with given expressionthen to get
Sum(...)
&Count(...)
of field do like thisinvoices[0].total_amount__sum
&invoices[0].number_of_invoices__count