简体   繁体   English

如何在Django中获得同一类的先前对象的总值?

[英]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.

相关问题 库存项目。 如何在Django的查询集中合计同名对象的值 - Inventory project. How to total the value of same name objects in queryset in Django 如何在同一类的Django对象上设置层次结构? - How to set hierarchy on Django objects of the same class? 减少循环遍历多个对象以获取价值的时间 Django - Reduce time for Loop over multiple objects to get value Django Django如何计算对象值的每月利息? - Django How to calculate monthly interest over an objects value? 如果前一个打印值与新值相同,如何在 python 中打印上一行? - How to print over the previous line in python if the previous printed value is the same as the new one? Django:在模板中的同一个循环中循环超过 2 个对象 - Django: Loop over 2 objects in same loop in template 如何在 Python 中迭代类对象并更改属性值 - How to iterate over the class objects and change the property value in Python 如何在 Django 中获取总持续时间 - How to get total duration in Django 遍历 go 列中的每个值,得到同一列中的 5 个先前值 - Iterating over each value in column go get 5 previous values in same column 如何遍历 class 个对象的列表,并计算出有多少个属性是相同的? - How to iterate through a list of class objects and total up how many attributes are the same?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM