如何计算django模型中@属性函数的总和?
how to calculate sum of @property function in django model?
我想计算 total_amount
属性 的总和。这是我的 models.py
class Orders(models.Model):
order_id = models.AutoField(primary_key=True)
order_item = models.ForeignKey('Product', models.DO_NOTHING, db_column='order_item', blank=True, null=True,
related_name='ordered_item')
order_status = models.CharField(max_length=100, blank=True, null=True)
delivery_address = models.TextField(blank=True, null=True)
customer = models.ForeignKey('User', models.DO_NOTHING, db_column='customer', blank=True, null=True)
quantity = models.IntegerField()
date_time = models.DateTimeField()
@property
def total_amount(self):
rate = Product.objects.get(pk=self.order_item.product_id)
total_amount = rate.price * self.quantity
return total_amount
@property
def unit_rate(self):
rate = Product.objects.get(pk=self.order_item.product_id)
return rate.price
您不需要 属性 方法。而是像这样使用 annotate
:
from django.db.models import Sum, F, ExpressionWrapper, DecimalField
Orders.objects.filter(date_time__month=6).annotate(
total_amount = ExpressionWrapper(
F('order_item__price')*F('quantity'),
output_field=DecimalField()
)
).aggregate(monthly_total=Sum('total_amount'))['monthly_total']
我想计算 total_amount
属性 的总和。这是我的 models.py
class Orders(models.Model):
order_id = models.AutoField(primary_key=True)
order_item = models.ForeignKey('Product', models.DO_NOTHING, db_column='order_item', blank=True, null=True,
related_name='ordered_item')
order_status = models.CharField(max_length=100, blank=True, null=True)
delivery_address = models.TextField(blank=True, null=True)
customer = models.ForeignKey('User', models.DO_NOTHING, db_column='customer', blank=True, null=True)
quantity = models.IntegerField()
date_time = models.DateTimeField()
@property
def total_amount(self):
rate = Product.objects.get(pk=self.order_item.product_id)
total_amount = rate.price * self.quantity
return total_amount
@property
def unit_rate(self):
rate = Product.objects.get(pk=self.order_item.product_id)
return rate.price
您不需要 属性 方法。而是像这样使用 annotate
:
from django.db.models import Sum, F, ExpressionWrapper, DecimalField
Orders.objects.filter(date_time__month=6).annotate(
total_amount = ExpressionWrapper(
F('order_item__price')*F('quantity'),
output_field=DecimalField()
)
).aggregate(monthly_total=Sum('total_amount'))['monthly_total']