From 0849cfa25af85a87958e2f6e93f61ea325b59268 Mon Sep 17 00:00:00 2001 From: C4 Patino Date: Tue, 30 Aug 2022 23:33:06 -0500 Subject: [PATCH] Added functionality to finalize house points --- housewars/admin.py | 24 +++++++++++++++++++----- housewars/models/House.py | 10 ++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/housewars/admin.py b/housewars/admin.py index 6ad2b4b..dd42bd2 100644 --- a/housewars/admin.py +++ b/housewars/admin.py @@ -1,5 +1,7 @@ from django.contrib import admin -from django.db.models import Sum +from django.contrib import messages +from django.utils.translation import ngettext +from django.db.models import Sum, F from django.db.models.functions import Coalesce from .models import Activity, House, Teacher, PointsEntry, UserEntry @@ -36,17 +38,29 @@ class ActivityAdmin(admin.ModelAdmin): @admin.register(House) class HouseAdmin(admin.ModelAdmin): list_display = ('name', 'points', 'current_points', 'total_points') + actions = ['finalize_points'] @admin.display(description='Current Housewars Points') def current_points(self, obj): - return PointsEntry.objects.filter(house__name=obj.name).aggregate(points__sum=Coalesce(Sum('points'), 0)).get('points__sum') + return obj.current_points @admin.display(description='Total Points') def total_points(self, obj): - return self.current_points(obj) + obj.points + return obj.total_points + + @admin.action(description='Finalize selected house points') + def finalize_points(self, request, queryset): + updated = queryset.update( + points=queryset.aggregate(points__sum=Coalesce(Sum('pointsentry__points'), 0)).get('points__sum') + F('points')) + PointsEntry.objects.filter(pk__in=queryset).delete() + self.message_user(request, ngettext( + '%d story was successfully marked as published.', + '%d stories were successfully marked as published.', + 1, + ) % 1, messages.SUCCESS) -@admin.register(Teacher) +@ admin.register(Teacher) class TeacherAdmin(admin.ModelAdmin): fieldsets = [ ('Personal Information', {'fields': [ @@ -58,7 +72,7 @@ class TeacherAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'grade', 'activity') -@admin.register(UserEntry) +@ admin.register(UserEntry) class EntryAdmin(admin.ModelAdmin): fieldsets = [ ('Personal Information', {'fields': [ diff --git a/housewars/models/House.py b/housewars/models/House.py index 81df7e0..e6b0b4c 100644 --- a/housewars/models/House.py +++ b/housewars/models/House.py @@ -1,10 +1,20 @@ from django.db import models +from django.db.models import Sum +from django.db.models.functions import Coalesce class House(models.Model): name = models.CharField(max_length=100) points = models.IntegerField(default=0) + @property + def current_points(self): + return self.pointsentry_set.aggregate(points__sum=Coalesce(Sum('points'), 0)).get('points__sum') + + @property + def total_points(self): + return self.current_points + self.points + def __str__(self): return f"{self.name}"