Suppose I have a Book model with a language field and a foreign key to a Publisher model.
Currently I use a Count annotation in a custom Publisher manager to allow me to add to the admin a sortable column with the number of books by each publisher. (see How to add a sortable coun开发者_运维知识库t column to the Django admin of a model with a many-to-one relation? )
My problem now is that I need to have a different column count for the books published in each language.
Is there any way to make the annotation subject to a filter of the related model?
You can use the double underscore __
for this purpose. Something like this (snippet taken from question linked to by OP):
class PublisherManager(models.Manager):
def get_query_set(self):
return super(PublisherManager,self).get_query_set().annotate(lang_count=Count('book__language'))
精彩评论