Home > database >  TypeError: unsupported operand type(s) for : 'int' and 'Time'
TypeError: unsupported operand type(s) for : 'int' and 'Time'

Time:06-17

I want to sum minutes keeping in my table.

class Time(models.Model):
    value = models.PositiveIntegerField(null=True)

I'm trying to sum minutes in def function:

def sum(request):
   times = ..._set.all()
    for time in times:
        total_min = total_min   time

Then I have TypeError:

unsupported operand type(s) for : 'int' and 'Time'.

The problem appears because I'm trying to summarize values of different types: int object type. And to solve the problem I need to convert object model PositiveIntegerField into int. But how can I do this not in class, but in def function?

CodePudding user response:

Here time is a Time object, and you can not add an int and a Time object together. What you can do is take the .value of the Time object. Since .value can be None, we should work with time.value or 0 to add 0 in case the value is None or 0, so:

def sum(request):
    some_object = …
    total_min = 0
    for time in some_object.time_set.all():
        total_min  = time.value or 0

But this is not very efficient: it requires to fetch all Time objects from the database, and then performs the aggregation in at the Django/Python layer. You can do this at the database side with a Sum expression [Django-doc] in an .aggregate(…) clause [Django-doc]:

from django.db.models import Sum

def sum(request):
    some_object = …
    total_min = some_object.time_set.aggregate(total=Sum('value'))['total']

Note: Please do not name a variable sum, it overrides the reference to the sum builtin function [Python-doc]. Use for example sum_view.

  • Related