Suppose I have a Book model containing a foreign key to a Publisher model.
How can I display in the Django admin a column with the number of books published by each publisher, in a way that I can use the built-in sorting?
Suppose I have a Book model containing a foreign key to a Publisher model.
How can I display in the Django admin a column with the number of books published by each publisher, in a way that I can use the built-in sorting?
Try something like this:
class PublisherAdminWithCount(Admin):
def book_count(self, obj):
return obj.book_set.count()
list_display = ('user_count',)
admin.site.register(Group, PublisherAdminWithCount)
Try this:
make a new Manager (and aggregate with count on the book relation field):
class PublisherManager(models.Manager):
def get_query_set(self):
return super(PublisherManager,self).get_query_set().annotate(pubcount=Count('book'))
sort it on pubcount
:
class Publisher(models.Model):
......
objects = PublisherManager()
class Meta:
ordering = ('pubcount',)
You should indeed start off with adding:
class PublisherManager(models.Manager):
def get_query_set(self):
return super(PublisherManager,self).get_query_set().annotate(pubcount=Count('book'))
But the correct way to add it as a sortable field is:
class Publisher(models.Model):
......
objects = PublisherManager()
def count(self):
return self.pubcount
count.admin_order_field = 'pubcount'
And then you can just add 'count' to the list_display attribute of model admin in admin.py