簡體   English   中英

Django 注釋總和

[英]Django Annotate Sum

我正在嘗試為查詢集中有幾行的列獲得一個簡單的總和。 我的直接問題是 (a) 如何設置get_queryset()以包含一列的總和以及 (b) 如何在模板中訪問該元素? 按照這個問題:

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

有提供了兩個答案-一個使用.aggregate()我不相信回報查詢集和方法.annotate()方法,我相信追加到查詢集的項目。

因此,我希望以下內容會在此視圖中向對象列表添加另一個項目:

#views.py
def get_queryset(self):
    # generate table and filter down to a subquery.
    queryset = ItemPrice.objects.filter(<some_filter>)
    # sum the price for each row in the subquery.
    queryset = queryset.annotate(totals=Sum('price'))
    return queryset

然后在模板中,我將能夠像這樣遍歷對象列表:

#template.html
{% for item in object_list %}
    {{ item }}
{% endfor %}

期望其中一個項目(最后一個項目?)是price_sum並且余額可以作為price_sum.price訪問。

但是,當我將以下內容添加到我的模板時,我會得到每個訂單項的價格 - 沒有總和。

{% for item in object_list %}
    {{ item.totals }}
{% endfor %}

但是,我無法訪問該項目。 不知道是get_queryset()的視圖修改的問題還是模板中的問題?

如果你會使用:

ItemPrice.objects.filter(<some_filter>).annotate(totals=Sum('price'))

總計將始終與“價格”相同

注釋(關於總和)使用如下:

如果你有這些模型:

class ItemPrice( models.Model ):
    price = models.DecimalField ( max_digits = 8, decimal_places=2 )
    other_model = models.ForeignKey(
          to=OtherModel, 
          related_name="item_prices", 
          on_delete=models.SET_NULL
    )

# related_name - if I set related_name I can use like this
# other_model_object.item_prices.all() - this code return all 
# ItemPrices with other_model_id=other_model_object.id

class OtherModel(models.Model):
    some_field = models.CharField(max_lenght=256)

並且您想要所有具有指向一個 OtherModel 的外鍵的 ItemPrices 的所有價格,您應該使用以下代碼:

queryset = OtherModel.objects.annotate(
       total_prices=Sum('item_prices__price')
).filter(<your_filters>)

之后你可以使用:

for obj in queryset:
    print(obj.total_prices)

或者,如果您需要所有價格的總和,您應該使用聚合

ItemPrices.objects.aggregate(all_sum=Sum('price'))

這段代碼像這樣返回字典(或類似的東西,我記不太清了)

{'all_sum': 1250}

all_sum - 數據庫中表中所有對象的總和

如果要將數據添加到模板

queryset = ItemPrice.objects.filter(<your_filter>)
totals = queryset.aggregate(sum=Sum('price').get('sum')

context  = {
    'object_list': queryset,
    'totals': totals,
}
render(request, '<name_of_your_template>.html', context)

並在您的模板中

{% for item in object_list %}
    # price of item
    {{ item.price }}
{% endfor %}
# total price
{{ totals }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM