I want a list view in the Django admin interface to display aggregates of the data. e.g. For a model with the fields employee_name, salary and month, I want the list to include fields like total_salary_paid and cumulative_of_month_salaries_paid. How can I do this?
Here's a snippet from a recent project of mine. It adds a column in the admin for "are there any entries in this M2M related table?" and another for "what's the count of entries in this M2M related table?". You could do similar things with the other aggregate functions Django offers.
from django.db.models import Count
from django.contrib import admin
class ExpertModelAdmin(admin.ModelAdmin):
def num_companies(self, obj):
"""# of companies an expert has."""
return obj.num_companies
num_companies.short_description = "# companies"
def has_video(self, obj):
"""Does the expert have a video?"""
return bool(obj.has_video)
has_video.short_description = "video?"
has_video.boolean = True
def get_queryset(self, request):
"""Use this so we can annotate with additional info."""
qs = super(ExpertModelAdmin, self).get_queryset(request)
return qs.annotate(num_companies=Count('company', distinct=True),
has_video=Count('mediaversion', distinct=True))