Add Season model to teams app: define fields, constraints, meta options, and utility methods for date range and current season tracking.
This commit is contained in:
@@ -1,3 +1,44 @@
|
||||
from django.db import models
|
||||
import datetime
|
||||
|
||||
# Create your models here.
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from rules import is_superuser
|
||||
from rules.contrib.models import RulesModel
|
||||
|
||||
|
||||
class Season(RulesModel):
|
||||
start_date = models.DateField(_("start date"))
|
||||
end_date = models.DateField(_("end date"))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("season")
|
||||
verbose_name_plural = _("seasons")
|
||||
ordering = ["start_date"]
|
||||
rules_permissions = {"add": is_superuser, "view": is_superuser, "change": is_superuser, "delete": is_superuser}
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["start_date", "end_date"], name="season_start_date_end_date_unique", violation_error_message=_("Start and end date for a given season must be unique")),
|
||||
models.CheckConstraint(condition=models.Q(start_date__lt=models.F("end_date")), name="season_start_date_lt_end_date", violation_error_message=_("Start date must be before end date.")),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return _("Season '{start_date} - '{end_date}").format(start_date=self.start_date.strftime("%y"), end_date=self.end_date.strftime("%y"))
|
||||
|
||||
@property
|
||||
def is_current(self) -> bool:
|
||||
return self.start_date <= timezone.now().date() <= self.end_date
|
||||
|
||||
@property
|
||||
def date_range(self) -> tuple[datetime.date, datetime.date]:
|
||||
return self.start_date, self.end_date
|
||||
|
||||
@classmethod
|
||||
def for_date(cls, current_date: datetime.date | None = None, values_only: bool = False) -> "tuple[datetime.date, datetime.date] | Season":
|
||||
if current_date is None:
|
||||
current_date = timezone.now().date()
|
||||
|
||||
season = cls.objects.get(start_date__lte=current_date, end_date__gte=current_date)
|
||||
|
||||
if values_only:
|
||||
return season.date_range
|
||||
return season
|
||||
|
||||
Reference in New Issue
Block a user