I'm trying to make a function that can dynamically builds a Django QuerySet. But for some reason it keeps giving a NameError
... Can anybody see what's going wrong?
Doesn't work:
from django.db.models import Sum
sum_fields = ['subtotal', 'id']
subtotal = Invoice.objects.filter(id__in=id_list).aggregate(**{field: Sum(field) for field in sum_fields})
The error given is NameError: global name 'Sum' is not defined
. But... I'm importing it just before I try to do the dictionary comprehension.
This does work:
from django.db.models import Sum
sum_fields = ['subtotal', 'id']
subtotal = Invoice.objects.filter(id__in=id_list).aggregate(**dict([(field, Sum(field)) for field in sum_fields]))
The last version works and does what it should do, but I want to know what's wrong with my dictionary comprehension.