0

I have a running total template tag which looks like

from django.template import Library 

register = Library() 

@register.filter
def running_total(list, var_name):
    return sum(getattr(obj, var_name) or 0 for obj in list)

It works when I need a running total in normal querysets, but when I use a annotated queryset I get the exception 'dict' object has no attribute 'total'.

When I print a normal queryset in my template I get [<Item: Item #1>], but when I print a annotated queryset I get a list with a tuple [{'total_amount': Decimal('0.00'), ...].

Should I somehow convert the list in my templatetag?

I've tried adding

list = list(list)

but it still doesn't work.

1
  • use a better name than list. you are overriding the default type. Commented Sep 2, 2014 at 13:53

1 Answer 1

1
arr = []
for obj in list:
    if isinstance(obj, dict):
        arr.append(obj[var_name] if var_name in obj else 0)
    else:
        arr.append(getattr(obj, var_name) or 0)
return sum(arr)

The reason is that elements in annotated queryset is not model instance anymore, it's dict.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.