[英]How to Get queryset not dict django aggregate
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--->返回dict--->
{'total_amount': Decimal('17700.00'), 'number_of_invoices': 2}
but I want queryset how can i do that.. Thanks for any help但我想要查询集我该怎么做..感谢您的帮助
This is what aggregate do:)这就是聚合所做的:)
You can add a DecimalField
to Invoice
model, that aggregates total_amount
during before every save.您可以将DecimalField
添加到Invoice
model,在每次保存之前汇总total_amount
。 I suggest signals for that.我建议为此发出信号。
class YourAppConfig(AppConfig):
...
def ready(self):
from . import signals
from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import Invoice
@receiver(pre_save, sender=Invoice)
def total_amount_aggregation(sender, instance, *args, **kwargs):
instance.total_amount = # aggregate desired amount here
You have to set similar signals for your Order
, so if you change Order
object, the related Invoice
object will be recalculated.您必须为您的Order
设置类似的信号,因此如果您更改Order
object,相关的Invoice
object 将被重新计算。
After that QuerySet
will stay as QuerySet
and every object will have always caclulated field.之后QuerySet
将保持为QuerySet
并且每个 object 将始终具有 caclulated 字段。
Instead of using .aggregate(...)
use .annotate(...)
this will return a QuerySet with given expression而不是使用.aggregate(...)
使用.annotate(...)
这将返回一个带有给定表达式的QuerySet
from django.db.models import Sum, Count
invoices = Invoice.objects.annotate(
total_amount=Sum('order__order_items__amount'),
number_of_invoices=Count('pk', distinct=True)
)
then to getSum(...)
&Count(...)
of field do like this invoices[0].total_amount__sum
& invoices[0].number_of_invoices__count
然后获取字段的Sum(...)
和Count(...)
执行此操作invoices[0].total_amount__sum
& invoices[0].number_of_invoices__count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.