Files
training.django/source/advanced/various/admin/room.py
Steve Kossouho e3ebf6bf4f Add documentation and source
Added documentation, source and extra files.
2025-07-02 20:26:50 +02:00

52 lines
1.5 KiB
Python

from django.contrib import admin
from django.db import models
from django.db.models import F
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _
from various.models import Room
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):
"""
Admin configuration for rooms.
"""
list_display = ["id", "name", "length", "width", "height", "get_volume_display"]
list_editable = ["name", "length", "width", "height"]
actions = ["action_fix_minimum"]
def get_queryset(self, request):
"""
Change queryset to add a computed field for volume.
Args:
request: HTTP
"""
return super().get_queryset(request).annotate(volume=F("width") * F("length") * F("height"))
def get_volume_display(self, obj: Room) -> str:
return f"{obj.get_volume()} cm³"
get_volume_display.short_description = _("area")
get_volume_display.admin_order_field = "volume"
def action_fix_minimum(self, request: HttpRequest, queryset: models.QuerySet):
"""
Change room dimensions to have at least 1cm in every axis.
Args:
request: HTTP request.
queryset: selected rooms.
"""
for room in queryset: # type: Room
room.width = max(1, room.width)
room.length = max(1, room.length)
room.height = max(1, room.height)
room.save()
self.message_user(request, _("The selected rooms have been updated."))