Django: Calculate the Sum of the column values through query

前端 未结 4 1390
生来不讨喜
生来不讨喜 2020-12-04 10:35

I have a model

class ItemPrice( models.Model ):
     price = models.DecimalField ( max_digits = 8, decimal_places=2 )
     ....

I tried thi

相关标签:
4条回答
  • 2020-12-04 11:07

    You're probably looking for aggregate

    from django.db.models import Sum
    
    ItemPrice.objects.aggregate(Sum('price'))
    # returns {'price__sum': 1000} for example
    
    0 讨论(0)
  • 2020-12-04 11:07

    Using cProfile profiler, I find that in my development environment, it is more efficient (faster) to sum the values of a list than to aggregate using Sum(). eg:

    sum_a = sum([item.column for item in queryset]) # Definitely takes more memory.
    sum_b = queryset.aggregate(Sum('column')).get('column__sum') # Takes about 20% more time.
    

    I tested this in different contexts and it seems like using aggregate takes always longer to produce the same result. Although I suspect there might be advantages memory-wise to use it instead of summing a list.

    0 讨论(0)
  • 2020-12-04 11:22

    Annotate adds a field to results:

    >> Order.objects.annotate(total_price=Sum('price'))
    <QuerySet [<Order: L-555>, <Order: L-222>]>
    
    >> orders.first().total_price
    Decimal('340.00')
    

    Aggregate returns a dict with asked result:

    >> Order.objects.aggregate(total_price=Sum('price'))
    {'total_price': Decimal('1260.00')}
    
    0 讨论(0)
  • 2020-12-04 11:28

    Use .aggregate(Sum('column'))['column__sum'] reefer my example below

    sum = Sale.objects.filter(type='Flour').aggregate(Sum('column'))['column__sum']
    
    0 讨论(0)
提交回复
热议问题