from django.db import models from django.db.models import Q from users.models import CustomUser class Event(models.Model): MORNING, AFTERNOON, EVENING = range(3) TIME_SLOTS = { MORNING: "voormiddag", AFTERNOON: "namiddag", EVENING: "avond", } date = models.DateField() time = models.IntegerField(choices=TIME_SLOTS.items(), default=MORNING) capacity = models.IntegerField(default=6) def __str__(self): return f"{self.date} {self.TIME_SLOTS[self.time]}" def time_str(self): return Event.TIME_SLOTS[self.time] def count_with_status(self, status): return self.eventregistration_set.filter(state=status).count() def count_interested(self): return self.count_with_status(EventRegistration.INTERESTED) def count_admitted(self): return self.count_with_status(EventRegistration.ADMITTED) def registration_of(self, user): if not user.is_authenticated: return None registrations = self.eventregistration_set.filter(user=user).all() if not registrations: return None assert len(registrations) == 1, "Registrations should be unique per user and event" return registrations[0] class EventRegistration(models.Model): INTERESTED = "I" ADMITTED = "A" REGISTRATION_STATE = { INTERESTED: "op wachtlijst", ADMITTED: "bevestigd", } event = models.ForeignKey(Event, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) state = models.CharField(max_length=1, choices=REGISTRATION_STATE.items()) class Meta: constraints = [ models.UniqueConstraint( fields=["event", "user"], name="register_only_once" ), ] def __str__(self): return f"Reservation[{self.user.username}:{self.event.date}:{self.state}]" def state_str(self): return EventRegistration.REGISTRATION_STATE[self.state]