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 I understand correctly, you know how to write a Python function to query the database and compute the aggregate, you just don't know where to put this function to have the result show up in the Django admin.
This is actually in the documentation for ModelAdmin.list_display
(the paragraph starting with "If the string given is a method of the model...").
This is their example:
from django.db import models
from django.contrib import admin
from django.utils.html import format_html
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
def colored_name(self):
return format_html('<span style="color: #{0};">{1} {2}</span>',
self.color_code,
self.first_name,
self.last_name)
colored_name.allow_tags = True
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'colored_name')
In your case, just change your equivalent of colored_name()
to compute the aggregate, and it should show up as a field in the Django admin.
© 2022 - 2024 — McMap. All rights reserved.