Django: how to sum up numbers in django

i want to calculate the total sales and display the total price, i dont know how to write the function to do this. I have tried writing a little function to do it in models.py but it working as expected. This is what i want, i have a model named UserCourse which stored all the purchased courses, now i want to calculate and sum up all the price of a single course that was sold.

models.py

class Course(models.Model):
    course_title = models.CharField(max_length=10000)
    slug = models.SlugField(unique=True)
    price = models.IntegerField(default=0)

class UserCourse(models.Model):
    user = models.ForeignKey(User , null = False , on_delete=models.CASCADE)
    course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)

and also how do i filter this models in views.py so i can display the total price of courses a particular creator have sold.

https://docs.djangoproject.com/en/4.0/topics/db/aggregation/

1 Like