Django ORM: Getting Reverse Dict

I have a model Chairwith a text box color. I want to get a dict in the following format:

{'red': 53,
 'green': 1582,
 'cyan': 73}

Each number is the number of rows of a chair with this color, counting all the chairs in the database.

How can I do this using Django ORM? (My database is Postgres, if that matters.)

+4
source share
1 answer
 Chair.objects.all().values('color').annotate(count=Count("color")).order_by()

More details here https://docs.djangoproject.com/en/dev/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

+1
source

Source: https://habr.com/ru/post/1527089/


All Articles