Dynamic verbose_name_plural to display number of models in admin panes

330 views
Skip to first unread message

Alexey Moskvin

unread,
Jun 5, 2011, 4:56:09 AM6/5/11
to Django users
Hi, I need to display number of objects at main django site admin
page.
For example, in list of models I need to display
Elephants (6)
instead of
Elephants
I added this code to my model:

class Elephant(models.Model):
....
class Meta:
verbose_name_plural = 'Elephant ' + '(' +
unicode(count_elephants()) + u')'

where count_elephants() calculates number of objects. The problem is
that verbose_name_plural is calculated at server start and is not
called when I delete/insert objects, so this calculated value becomes
irrelevant.
Is it possible to do it in correct way?
Thanks!

Tim Shaffer

unread,
Jun 5, 2011, 8:50:44 AM6/5/11
to django...@googlegroups.com
You could probably do it using a signal. Every time a record is created or deleted, you can update the verbose_name_plural with the current count.

from django.db.models.signals import post_save, post_delete

def update_verbose_name(sender, **kwargs):
    Elephant._meta.verbose_name_plural = 'elephants (%s)' % Elephant()

post_delete.connect(update_verbose_name, sender=Elephant)
post_save.connect(update_verbose_name, sender=Elephant)

Alexey Moskvin

unread,
Jun 5, 2011, 12:02:33 PM6/5/11
to Django users
Tim, thanks for your help!
Also, I've found another solution for this problem:
http://stackoverflow.com/questions/6241906/display-number-of-instances-for-each-model-in-djangos-admin-index
Reply all
Reply to author
Forward
0 new messages