S
S
SexyHair2020-01-15 12:41:49
Django
SexyHair, 2020-01-15 12:41:49

How to enable sorting by annotated/calculated field in django admin?

There is a Post model - a post on the site, there is a Language model - the language in which the post is written. OneToMany connection, I want to display the "Number of posts" field in the Language admin panel with the ability to sort in forward / reverse order. I added the field, but it’s impossible to add sorting to it.
If you uncomment the last line, sorting will appear, but each language will be duplicated as many times as the number of posts this language uses (using distinct in the overridden get_queryset had no effect). How to be human?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-01-15
@SexyHair

in get_queryset add not distinct, but annotate with Count

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question