Django 在 fk_set 上注释总和
Django annotate sum on fk_set
我正在尝试注释相关集中的字段总和:
我的模特:
class Report(models.Model):
class ReportCommissionPosition(models.Model):
report = models.ForeignKey(Report)
reservation = models.OneToOneField("reservations.Reservation")
class Reservation(models.Model):
class Payment(models.Model):
amount = models.DecimalField(max_digits=10, decimal_places=2)
reservation = models.ForeignKey('reservations.Reservation')
PAYMENT_TYPES=(
('TRANS', 'TRANS'),
('SELL', 'SELL'),
payment_accounting_type = models.CharField(max_length=50, choices=PAYMENT_TYPES)
我需要用两个字段注释 report.reportcommissionposition_set 的每个位置:
trans_amount - 支付会计类型== 'SELL'的所有支付总和(通过预订=>支付)
sum_amount - 付款会计类型==的所有付款总和'TRANSFER'(通过预订=>付款)
我试过:
for position in commission_position:
position.sell_pay = position.reservation.payment_set.filter(payment_accounting_type='SELL').aggregate(amount=Sum('amount'))['amount']
但这会为每个元素创建新的查询。
有什么想法吗?
您可以用以下方式注释它们:
myreport.reportcommissionposition_set.annotate(
trans_amount=Sum(
'reservation__payment__amount',
<strong>filter=Q(reservation__payment__type='SELL')</strong>
),
sum_amount=Sum(
'reservation__payment__amount',
<strong>filter=Q(reservation__payment__type='TRANS')</strong>
)
)
myreport
的 ReportCommissionPosition
对象将有两个额外的字段:.trans_amount
和 .sum_amount
以及 SELL
和 [=15= 的总和] 付款。
我正在尝试注释相关集中的字段总和:
我的模特:
class Report(models.Model):
class ReportCommissionPosition(models.Model):
report = models.ForeignKey(Report)
reservation = models.OneToOneField("reservations.Reservation")
class Reservation(models.Model):
class Payment(models.Model):
amount = models.DecimalField(max_digits=10, decimal_places=2)
reservation = models.ForeignKey('reservations.Reservation')
PAYMENT_TYPES=(
('TRANS', 'TRANS'),
('SELL', 'SELL'),
payment_accounting_type = models.CharField(max_length=50, choices=PAYMENT_TYPES)
我需要用两个字段注释 report.reportcommissionposition_set 的每个位置:
trans_amount - 支付会计类型== 'SELL'的所有支付总和(通过预订=>支付) sum_amount - 付款会计类型==的所有付款总和'TRANSFER'(通过预订=>付款)
我试过:
for position in commission_position:
position.sell_pay = position.reservation.payment_set.filter(payment_accounting_type='SELL').aggregate(amount=Sum('amount'))['amount']
但这会为每个元素创建新的查询。
有什么想法吗?
您可以用以下方式注释它们:
myreport.reportcommissionposition_set.annotate(
trans_amount=Sum(
'reservation__payment__amount',
<strong>filter=Q(reservation__payment__type='SELL')</strong>
),
sum_amount=Sum(
'reservation__payment__amount',
<strong>filter=Q(reservation__payment__type='TRANS')</strong>
)
)
myreport
的 ReportCommissionPosition
对象将有两个额外的字段:.trans_amount
和 .sum_amount
以及 SELL
和 [=15= 的总和] 付款。