Search code examples
pythondjangogeneratorincrement

Python generator with increment


I have a loop:

total = 0
for s in sums:
    total += s[0]

where sums is a list of objects from the database, retrieved by Django:

sums = Source_types.objects.values_list('source_sum')

I'd like to move this code into a one-line generator.


Solution

  • Use the sum() function with a generator expression:

    total = sum(s[0] for s in sums)
    

    However, the Django ORM can be used to tell the database to do the summing here, using aggregation:

    from django.db.models import Sum
    
    total = Source_types.objects.aggregate(Sum('source_sum'))