python – Django admin: how to add the sum of all the records of a model?


I am creating an accounting application. I created the model for the transactions as follows:


In the admin I made all the columns to be displayed and also the filters for each column, but I need the total of the transaction amounts to be added in a new row.

Is there any way to add this kind of thing in the admin? Add a Count for example.


Answering your question:

Is there any method of adding this kind of thing in the admin?


What you have to do first is to override the ModelAdmin.changelist_view method, what you need is a Sum , not a Count :

from django.contrib import admin
from django.db.models import Sum
from .models import Transacciones

class TransaccionesAdmin(admin.ModelAdmin):

    def changelist_view(self, request, extra_context=None):
        total = Transacciones.objects.aggregate(total=Sum('monto'))['total']
        context = {
            'total': total,
        return super(TransaccionesAdmin, self).changelist_view(request, extra_context=context), TransaccionesAdmin)

You also need to override the admin template , this can be achieved by copying the template from the path contrib/admin/templates/admin/change_list.html and pasting it into your project path templates/admin/nombre_app/transacciones/ .

It only remains to show the total result in the template and you achieve this by showing it as you would in any other template.


{% block content %}
   {{ total }}
{% endblock %}
Scroll to Top