我使用以下代码进行查询:
views.py:
reservations_table = Reservation.objects.all()
total_commission = 0
for reservation in reservations_table:
for city in COMMISSION_RATES.keys():
if reservation.city == city.upper():
total_commission += reservation.net_income * COMMISSION_RATES[city] / 100
for reservation in reservations_table:
for month in COMMISSION_PER_MONTH:
if reservation.checkout.month == month:
reservation.monthly = COMMISSION_PER_MONTH[month]
for reservation in reservations_table_city:
commission_amount_city += reservation.net_income * COMMISSION_RATES[form.cleaned_data['city']] / 100
models.py:
from django.db import models
class Reservation(models.Model):
reservation_code = models.CharField(max_length=150,unique=True)
checkin = models.DateField()
checkout = models.DateField()
flat = models.CharField(max_length=150)
city = models.CharField(max_length=150)
net_income = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.reservation_code
constants.py:
COMMISSION_RATES = {
'LONDON': 10,
'PARIS': 12,
'PORTO': 9,
}
如何做一个查询,但只使用Django ORM?因此,有3个查询可以工作,但我们的想法是使它们都是Django ORM。
您可以尝试这样做。小心,我的代码可能包含错误,这是唯一的方法来解决你的问题。
reservations_table = Reservation.objects.filter(
city__in=COMMISSION_RATES.keys(),
).annotate(
instance_commission=F('net_income') * COMMISSION_RATES[F('city')] / Value(100),
).aggregate(
total_commission=Sum('instance_commission')
)