doorcontrol: Reimplement HIDEvent.is_red as database function, add filter in admin

This commit is contained in:
Adam Goldsmith 2023-04-03 17:16:48 -04:00
parent a6c531c22f
commit 58d3787f9d
2 changed files with 59 additions and 21 deletions

View File

@ -3,11 +3,39 @@ from django.contrib import admin
from .models import HIDEvent
class IsRedFilter(admin.SimpleListFilter):
title = "Is Red"
parameter_name = "is_red"
def lookups(self, request, model_admin):
return (
("1", "Yes"),
("0", "No"),
)
def queryset(self, request, queryset):
if self.value() is None:
return queryset
else:
return queryset.filter(is_red=(self.value() == "1"))
@admin.register(HIDEvent)
class HIDEventAdmin(admin.ModelAdmin):
search_fields = ["description", "forename", "surname", "cardholder_id"]
list_display = ["door_name", "timestamp", "event_type", "description", "is_red"]
list_filter = ["door_name", "event_type"]
list_filter = [
"door_name",
"event_type",
IsRedFilter,
]
def get_queryset(self, request):
return super().get_queryset(request).with_is_red()
@admin.display(boolean=True)
def is_red(self, obj):
return obj.is_red
def has_add_permission(self, request, obj=None):
return False

View File

@ -1,8 +1,37 @@
from django.contrib import admin
from django.db import models
from django.db.models import ExpressionWrapper, Q
class HIDEventQuerySet(models.QuerySet):
def with_is_red(self):
"""Based on `function isRedEvent` from /html/hid-global.js on a HID EDGE EVO Solo"""
return self.annotate(
is_red=ExpressionWrapper(
Q(
event_type__in=[
1022,
1023,
2024,
2029,
2036,
2042,
2043,
2046,
4041,
4042,
4043,
4044,
4045,
]
),
output_field=models.BooleanField(),
)
)
class HIDEvent(models.Model):
objects = HIDEventQuerySet.as_manager()
class EventType(models.IntegerChoices):
DENIED_ACCESS_CARD_NOT_FOUND = 1022, "Denied Access: Card Not Found"
DENIED_ACCESS_ACCESS_PIN_NOT_FOUND = 1023, "Denied Access Access: PIN Not Found"
@ -89,25 +118,6 @@ class HIDEvent(models.Model):
return event_types.get(self.event_type, f"Unknown Event Type {self.event_type}")
@admin.display(boolean=True)
def is_red(self):
"""Based on `function isRedEvent` from /html/hid-global.js on a HID EDGE EVO Solo"""
return self.event_type in [
1022,
1023,
2024,
2029,
2036,
2042,
2043,
2046,
4041,
4042,
4043,
4044,
4045,
]
def __str__(self):
return f"{self.door_name} {self.timestamp} - {self.description}"