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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With