简体   繁体   中英

How to get total value over previous objects of the same class in Django?

I wrote my own billing software in 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.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM