Django使用聚合查询(价格乘以总数得到总价,并以总价排名)

自定义库存表(Stock)

class Stock(models.Model):
  amount = amount = models.IntegerField(verbose_name='数量')
  price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')

使用模板语法完成自定义查询:

Stock.objects.annotate(profit=F('price')*F('amount')).order_by('-profit')

—— 实现了以将所有库存总价格(单价*数量)由高到低的查询出来

posted @ 2024-02-15 20:14  wellplayed  阅读(12)  评论(0编辑  收藏  举报