我想顯示等于總價的總收入,而總價是約會模型中的一個欄位,我想要該特定欄位的計數,以便可以在 HTML 中顯示它。
class Appointment(models.Model):
# Invoicing Section
service_name = models.CharField(max_length=120, default='', blank=True, null=True)
total_price = models.CharField(max_length=100,default='', blank=True, null=True)
upfront_payment = models.CharField(max_length=100,default='', blank=True, null=True)
grand_total = models.CharField(max_length=100,default='', blank=True, null=True)
invoice_date = models.DateField(auto_now_add=True, blank=True, null=True)
invoice_type_choice = (
('EVCPLUS', 'EVCPLUS'),
('SH.SO', 'SH.SO'),
('USD', 'USD'),
)
invoice_type = models.CharField(max_length=50, default='', blank=True, null=True, choices=invoice_type_choice)
payment_status = models.CharField(max_length=10, choices=(('Pending', 'Pending'),
('Completed', 'Completed'), ('Canceled', 'Canceled')), default='Pending')
def __str__(self):
return self.patient.patient_name
我試著這樣做:
revenue = Appointment.objects.filter(total_price = Appointment.total_price).count()
return render(request, 'index.html', {
'current_user': current_user,
'sayfa': 'dashboard',
'yearly_patients': yearly_patients,
'monthly_appointments': monthly_appointments,
'yearly_patients_graph': yearly_patients_dict,
'monthly_appointments_graph':monthly_appointments_dict,
'donutDataGraph': donutData,
'appointments': appointments,
'doctors': doctors,
'revenue': revenue,
'search_patient_form': form,
'search_patient_form': search_patient_form
})
但它回傳 0 這是不正確的。
uj5u.com熱心網友回復:
因此,您的方法中存在一些問題。
首先,count()不計算總和,而是計算條目數。然而,這是一個好的開始,因為它聚合了資料庫中的記錄。
第二,.filter(total_price = Appointment.total_price)沒有任何意義。使用此陳述句,您可以將 db 值與欄位型別進行比較。此外,如果您想聚合所有行,您也不想過濾您的記錄。
第三,要求和,您需要有一個數字資料型別。但是,total_price是文本資料型別 ( CharField)。您將需要使用數字欄位(例如IntegerField整數金額,或DecimalField具有固定小數位數的小數金額):
total_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
請注意,更改資料型別將需要您進行遷移,并且將文本轉換為數字資料型別可能會失敗。但是,處理這種遷移超出了這個問題的范圍。
現在您有了數字資料型別,您可以進行數字聚合:
from django.db.models import Sum
revenue = Appointment.objects.aggregate(revenue=Sum('total_price'))['revenue']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/517421.html
下一篇:Django-聚合成陣列
