[英]How to get total value over previous objects of the same class in Django?
I wrote my own billing software in Django. 我在Django中编写了自己的计费软件。 In that I have a model called bills.
在那我有一个名为票据的模型。 Every bill has a price value.
每张账单都有价格。 Now I want to give the bill model a function that adds up the price values of all previous bills and the current one.
现在我想给账单模型一个函数,它将所有先前账单和当前账单的价格值相加。 This function is meant to give me a number of how much I've earned so far.
这个功能是为了给我一些到目前为止我赚了多少钱。
But every time I try to implement it I run into the problem that I can't use the bill class within the definition of itself. 但每次我尝试实现它时,我遇到的问题是我不能在自己的定义中使用bill类。
What is the best approach to add a function to my bill class that gets all the bill objects (including the current one) and adds up the price values? 向我的账单类添加功能以获取所有账单对象(包括当前账单对象)并将价格值相加的最佳方法是什么?
I'm sensing that I've misunderstood something, but why don't you just do something like this? 我感觉到我误解了一些东西,但你为什么不这样做呢?
class Bill(models.Model):
due_date = models.DateField()
price = models.IntegerField()
paid = models.BooleanField()
def get_previous_bills(self):
return Bill.objects.filter(due_date__lte=timezone.now(), paid=True)
def get_total_price(self):
return sum(p.price for p in self.get_previous_bills())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.