Skip to content

Commit

Permalink
Introduce TimespanMixins
Browse files Browse the repository at this point in the history
  • Loading branch information
b1rger committed Mar 13, 2023
1 parent 0c3bfec commit 377d608
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Empty file.
49 changes: 49 additions & 0 deletions apis_core/apis_metainfo/mixins/dt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# SPDX-FileCopyrightText: 2023 Birger Schacht
# SPDX-License-Identifier: MIT

"""
Date and Time related Mixins
"""

from django.db.models import DateTimeField, CharField
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _

from apis_core.helper_functions import DateParser


class TimespanMixin:
"""A simple mixin to implement a timespan"""

begin = DateTimeField(blank=True, null=True)
end = DateTimeField(blank=True, null=True)


class TimespanInvervalMixin(TimespanMixin):
"""A timespan mixin of which the begin and the end consist of invervals"""

begin_from = DateTimeField(blank=True, null=True)
begin_to = DateTimeField(blank=True, null=True)
end_from = DateTimeField(blank=True, null=True)
end_to = DateTimeField(blank=True, null=True)

def clean(self):
if self.begin_from > self.begin_to:
raise ValidationError(_("Begin from can not be greater than begin to."))
if self.end_from > self.end_to:
raise ValidationError(_("End from can not be greater than end to."))


class ParseTimespanIntervalMixin(TimespanMixin):
"""A timespan inverval mixin that allows to enter the date in a string field"""

begin_string = CharField(
max_length=255, blank=True, null=True, verbose_name=_("Begin")
)
end_string = CharField(max_length=255, blank=True, null=True, verbose_name=_("End"))

def save(self, *args, **kwargs):
if self.begin_string:
self.begin, self.begin_from, self.begin_to = DateParser(self.begin_string)
if self.end_string:
self.end, self.end_from, self.end_to = DateParser(self.end_string)

0 comments on commit 377d608

Please sign in to comment.