Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display total record count against models in django admin

Is there a neat way to make the record/object count for a model appear on the main model list in the django admin module?

I have found techniques for showing counts of related objects within sets in the list_display page (and I can see the total in the pagination section at the bottom of the same), but haven't come across a neat way to show the record count at the model list level.

like image 863
Rog Avatar asked Jun 15 '10 01:06

Rog


2 Answers

I would look into the models.Manager class. A subclass of Manager will allow you to add table-level functionality to your models. A Manager method can return any data you want and there is an interesting example in the Django DB API documentation. You may then be able to pull this into Admin by adding a admin inner class to your model.

like image 155
λ Jonas Gorauskas Avatar answered Nov 16 '22 08:11

λ Jonas Gorauskas


from django import template
from django.db.models.loading import get_model

register = template.Library()

@register.simple_tag()
def get_model_count(admin_url):
  app_label, model_name = admin_url.split('/')[:2]
  return get_model(app_label, model_name, seed_cache=False).objects.count()

Then copy and override "/templates/admin/index.html" from "django's contrib/admin/templates/index.html".

At the top add:

{% load NAME_OF_YOUR_TAG_FILE %}

Add the following call after the model name or wherever:

{% get_model_count model.admin_url %}

This fits nicely into this use case. You're done!

like image 3
Paul Kenjora Avatar answered Nov 16 '22 06:11

Paul Kenjora