I Have Written A Query that returns (rating, count)
result = list(Film.objects.values_list('rating').annotate(count=Count('rating')))
rating is a choice field of
rating = (
("5","Excellent"),
("4","Good"),
("3","Average"),
("2","Bad"),
("1","Very Bad"),
)
I currently get the result like this
[(5, 10), (4,8), (3,7), (2,1), (1,4)]
I wish to get the pairs like this
[("Excellent",10),("Good",8)...]
Is there anything I can do within the Query to get it ? Whats the best method to get the desired result ?
Something like get_foo_display within this one.
I think you can Case Function
to achieve this below.
from django.db.models import Case, CharField, When
Film.objects.annotate(proxy_rating=Case(
When(rating=5, then="Excellent"),
When(rating=4, then="Good"),
When(rating=3, then="Average"),
When(rating=2, then="Bad"),
When(rating=1, then="Very Bad"),
output_field=CharField()
)).values_list("proxy_rating").annotate(count=Count('rating'))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments