0

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.

Xudonax
  • 429
  • 4
  • 17
  • 2
    I think your syntax is wrong in your first code example. See http://stackoverflow.com/questions/14507591/python-dictionary-comprehension. From this answer it should be ``{field:Sun(field) for for field in sum_fields}``. for this to work you need to be Python version 2,7+. – krak3n May 13 '13 at 08:42
  • My first example was indeed wrong, I updated it to have a : instead of a ,. But it is still complaining about the global name 'Sum' not being defined :( The double for gave me a syntax error :( – Xudonax May 13 '13 at 11:29

0 Answers0