universitySemestersDates.py 1.72 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.db import models
2
from backend_app.models.abstract.module import Module, ModuleSerializer, ModuleViewSet
Florent Chehab's avatar
Florent Chehab committed
3
from backend_app.models.university import University
4
from rest_framework import serializers
Florent Chehab's avatar
Florent Chehab committed
5
6


Florent Chehab's avatar
Florent Chehab committed
7
8
def semester_error(semester_name):
    raise serializers.ValidationError(
9
10
        "Inconsistent {} semester dates".format(semester_name)
    )
Florent Chehab's avatar
Florent Chehab committed
11
12


13
class UniversitySemestersDates(Module):
Florent Chehab's avatar
Florent Chehab committed
14
15

    university = models.OneToOneField(
16
17
18
19
20
21
        University,
        on_delete=models.CASCADE,
        related_name="university_semesters_dates",
        primary_key=True,
        null=False,
    )
Florent Chehab's avatar
Florent Chehab committed
22
23
24
25
26
27

    spring_begin = models.DateField(null=True, blank=True)
    spring_end = models.DateField(null=True, blank=True)
    autumn_begin = models.DateField(null=True, blank=True)
    autumn_end = models.DateField(null=True, blank=True)

28

29
class UniversitySemestersDatesSerializer(ModuleSerializer):
30
31
    def validate(self, attrs):
        attrs = super().validate(attrs)
32

33
34
        s_b, s_e = attrs["spring_begin"], attrs["spring_end"]
        a_b, a_e = attrs["autumn_begin"], attrs["autumn_end"]
Florent Chehab's avatar
Florent Chehab committed
35
36
37

        def test(begin, end, name):
            ok = (begin is None and end is None) or (
38
39
                begin is not None and end is not None
            )
Florent Chehab's avatar
Florent Chehab committed
40
41
42
43
44
            if not ok:
                semester_error(name)
            if begin is not None and (begin > end):
                semester_error(name)

45
46
        test(s_b, s_e, "spring")
        test(a_b, a_e, "autumn")
Florent Chehab's avatar
Florent Chehab committed
47

48
        return attrs
Florent Chehab's avatar
Florent Chehab committed
49
50

    class Meta:
51
        model = UniversitySemestersDates
52
        fields = "__all__"
Florent Chehab's avatar
Florent Chehab committed
53
54


55
class UniversitySemestersDatesViewSet(ModuleViewSet):
56
57
    queryset = UniversitySemestersDates.objects.all()  # pylint: disable=E1101
    serializer_class = UniversitySemestersDatesSerializer