是否可以将python方法转换为djagno数据库方法?



我想按总价值排序我的查询,总价值是项目的外键我用下面的方法来计算总金额。

models.py

函数
def total(self):
total=0
for item in self.items.all():
if item.taxed==True:
total = total + item.amount + (item.amount*(self.tax)/(100))
else:
total = total + item.amount
return total

my query lookslike:

nvoices = Invoices.objects.all().order_by()

不能传递自定义函数来订购对象。这是因为order_by()实际上是由数据库执行的,而数据库不能运行Python代码。

但是看看你的total()函数,在我看来主要是一个聚合函数,我认为你可以通过使用一个自定义的聚合函数来得到你想要的,你将不得不在这里用SQL详细编写。

下面是使用标准SQL函数SUM的示例:
from django.db.models import Sum
Invoice.objects.annotate(total=Sum('item__amount')).all().order_by('-total')

这将返回所有带有附加字段totalInvoice对象,并按该字段降序排序。

您现在可以继续使用您的自定义函数替换Sum()。这里有一篇文章详细介绍了如何编写这样一个函数。

相关内容