From 0d900de02cfac729bc304deae097a2f654e185fc Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Fri, 28 Jun 2019 14:47:35 +0200 Subject: [PATCH] Compute and display consumable count and price in admin --- manuels/admin.py | 10 +++++++++- manuels/models.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/manuels/admin.py b/manuels/admin.py index 8d84db5..8dee69e 100644 --- a/manuels/admin.py +++ b/manuels/admin.py @@ -28,10 +28,18 @@ class TeacherAdmin(ExportMixin, admin.ModelAdmin): @admin.register(Level) class LevelAdmin(admin.ModelAdmin): - list_display = ['name', 'order'] + list_display = ['name', 'order', 'consumable_count', 'consumable_price'] list_editable = ['order'] list_display_links = ['name'] + def consumable_count(self, obj: Level): + return obj.consumable_count + consumable_count.short_description = 'Nombre de consommable(s)' + + def consumable_price(self, obj: Level): + return f'{obj.consumable_price:.2f}€' + consumable_price.short_description = 'Coût des consommables' + class BookResource(resources.ModelResource): class Meta: diff --git a/manuels/models.py b/manuels/models.py index 3e338dd..cc87d8d 100644 --- a/manuels/models.py +++ b/manuels/models.py @@ -8,6 +8,7 @@ from django.contrib.postgres.fields import CIEmailField from django.core.exceptions import ValidationError from django.core.mail import EmailMultiAlternatives from django.db import models +from django.db.models import Sum from django.template.loader import render_to_string from django.urls import reverse @@ -115,6 +116,17 @@ class Level(BaseModel): def __str__(self): return self.name + @property + def consumable_count(self): + return self.book_set.filter(consumable=True).count() + + @property + def consumable_price(self): + price = self.book_set.filter(consumable=True).aggregate(Sum('price')).get('price__sum', 0) + if price is None: + return 0 + return price + class Editor(BaseModel): class Meta: