Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin interface to display aggregates

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

like image 348
Rahul Attuluri Avatar asked Mar 19 '14 21:03

Rahul Attuluri


1 Answers

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))
like image 143
Joel Burton Avatar answered Sep 23 '22 18:09

Joel Burton