How to add all the values of a column - Django


I would like to know how to add all the data in a column of my database.

This is my model:

class Model(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    id = models.AutoField(primary_key=True)
    number = models.FloatField(default=0)
    created = models.DateTimeField(auto_now_add=True, null=True)

I would like to obtain the sum of all the data in the number field to then perform an operation, the methods I know are the following but I do not know how to use them:


I want to do something like that but I do not know how to apply it:

obj = Model.objects.all().filter(user=request.user)

variable_1 = 10    
variable_1 = 10 + obj.number  # La suma de todos los registros del campo number

thank you very much friends

asked by Yamamoto AY 01.09.2018 в 17:49

1 answer


I recommend that you review the documentation . What you want to do is obtained with the following query:

from django.db.models import Sum

The result is a dictionary that looks something like this:

{'number__sum': 10}

If you assign it to a variable, you would use it this way:

obj = Model.objects.all().aggregate(Sum('number'))
obj['number__sum'] += 1
print (obj)
>>> {'number__sum': 11}
answered by 02.09.2018 / 15:59