Home > Software engineering >  Trying to SUM filtered objects django
Trying to SUM filtered objects django

Time:04-04

guys i'm really new using Django, i'm trying to sum a filtered list of objects by datetime like this SQL

SELECT ((select sum(some_col) from some_table WHERE datte> now()-interval 1 day))

i tried something like this:

inidate = datetime.datetime.now() 
d_date= timezone.now() - timedelta(1)
query = Model.objects.filter(date__range=(d_date,inidate)).aggregate(sum('values'))

result>>>

TypeError: unsupported operand type(s) for  : 'int' and 'str'

CodePudding user response:

You should use a Sum expression [Django-doc], not the sum(…) builtin [python-doc], so:

from django.db.models import Sum

query = Model.objects.filter(
    date__gte=timezone.now() - timedelta(1)
).aggregate(Sum('values'))
  • Related