【问题标题】:how to calculate sum of @property function in django model?如何在 django 模型中计算@property 函数的总和?
【发布时间】:2020-10-13 10:39:03
【问题描述】:

我想计算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

【问题讨论】:

  • 看来你有一个功能可以做到这一点。你的问题到底是什么?
  • 例如,我想要月收入,那么我需要一个月内total_amount 列的总和。

标签: python django django-models django-rest-framework django-admin


【解决方案1】:

你不需要一个属性方法。而是像这样使用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']

【讨论】:

  • Exception Value:QuerySet.aggregate() received non-expression(s): <django.db.models.fields.DecimalField>.
  • 如果您不介意,请告诉我如何在 django admin 的不同表格中显示它?
  • 按要求?
  • 抱歉,有什么要求?仅供参考,您可以将此代码添加到属性方法中并在管理站点中使用。
  • 我认为它不在这个问题的范围内。你能问一个新的更详细的关于你想要实现的目标吗?谢谢
猜你喜欢
  • 2021-01-30
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 2020-04-18
相关资源
最近更新 更多