I want to use django admin interface to display aggregates of data in a model. Ex: Model has following fields [employee name, salary, month] I want aggregate table with fields [month, total_salary_paid, cumulative_of_month_salaries_paid]. how do I do this ?? I have searched internet but didn't find any way to do it..any reference or guidance would help
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))
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