[英]Django weighted percentage
我正在嘗試計算 Django 查詢中的加權百分比。
這是我的數據的示例:
id start_date agency_id area_id housetype_id no_of_changed price_change_percentage total
6716 2017-08-26 11 1 1 16 -0.09 35
6717 2017-08-26 11 1 3 44 -0.11 73
6718 2017-08-26 11 1 4 7 -0.1 12
6719 2017-08-26 11 1 5 0 0 4
6720 2017-08-26 11 1 6 0 0 1
6721 2017-08-26 21 1 1 0 0 1
6722 2017-08-26 34 1 1 0 0 1
6723 2017-08-26 35 1 1 0 0 1
6724 2017-08-26 38 1 1 0 0 1
這是我當前的代碼:
from django.db.models import F, FloatField, ExpressionWrapper
from app.models import PriceChange
def weighted_percentage(area_id, date_range, agency_id, housetype):
data = PriceChange.objects.filter(area_id=area_id,
start_date__range=date_range,
agency_id=agency_id,
)
if housetype:
data = data.filter(housetype=housetype) \
.values('start_date') \
.annotate(price_change_total=ExpressionWrapper((F('price_change_percentage') * F('no_of_changed')) / F('total'), output_field=FloatField())) \
.order_by('start_date')
else:
# what to do?
pass
x = [x['start_date'] for x in data]
y = [y['price_change_total'] for y in data]
return x, y
我想出了如何在定義房屋類型時進行計算並且我只需要從一行中獲取數據。 當我需要計算具有相同 start_date 的多行時,我不知道該怎么做。 我不想要每一行的值,而是每個 start_date 的值。
例如(兩行具有相同的 start_date、area_id、agency_id 但不同的 housetype_id): no_of_changed price_change_percentage total 16 -0.09 35 44 -0.11 73
計算采用偽代碼: ((no_of_changed[0] * price_changed_percentage[0]) + (no_of_changed[0] * price_changed_percentage[0])) / (total[0] + total[1]) = price_change_total
((16 * -0.09) + (44 * -0.11)/ (35 + 73) = -0.03148148
我正在使用 Django 1.11 和 Python 3.6。
您需要將表達式包裝在 Sum 表達式中。
添加以下導入:
from django.db.models import Sum
然后添加以下查詢
else:
data = data.values('start_date') \
.annotate(
price_change_total=ExpressionWrapper(
Sum(F('price_change_percentage') * F('no_of_changed')) / Sum(F('total')),
output_field=FloatField()
)
) \
.order_by('start_date')
這里發生的事情是,當您在annotate()
調用中使用諸如Sum
類的聚合表達式時,它會被轉換為數據庫中的group_by
查詢。 前面values()
子句中列出的所有列都用於創建group_by
查詢。
請參閱此博客文章以獲得進一步的解釋和結果 SQL 查詢的細分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.