1
You’re passing the string “Sum(blah)”, hence the error.
FList['total_size'] = Sum(FName)
But really there’s no reason to use kwargs here at all:
data=Department.objects.annotate(total_size=Sum(FName))
0
Simplify..
from django.db.models import Avg, Count, Sum
# let Fname has the name of the field to sum on, set by a user input
FName='size'
data=Department.objects.annotate(total_size=Sum(FName))
Since FName
is a string, you don;t need to wrap it with quotes. If you needed tto run a different function, say avg etc…
from django.db.models import Avg, Count, Sum
# let Fname has the name of the field to sum on, set by a user input
FName='size'
function_t = Sum # or Avg, or Count
data=Department.objects.annotate(total_size=function_t(FName))
I hope this helps you get down the path
- 'WSGIRequest' object has no attribute 'flash'
- Django Translation in Overridden Form
- How do I get username by user_id in Django?
- How to insert data for multiple tables/models from the same page of django admin?
- Add images to a children class
0
For those who really wanted to pass a kwarg
to annotate probably ’cause it is defined dinamically you have to do the following:
annotate_filters = {
'sum_foo': Count('foo', distinct=True),
}
if foo:
annotate_filters['sum_foo'] = Count('bar', distinct=True)
Foo.objects.annotate(**annotate_filters)
In this way you can manage different condition and pass them to the annotate function.
Happy coding.
- Django Rest Framework return True if relation exist
- Issue with custom template tags in Django?
- Django: class based views login
- Django concrete inheritance, __str__(self) in parent fails to pick attribute from child
- Unable to import custom module to other application (Django)
Source:stackexchange.com