universitySemestersDates.py 2.14 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.db import models
2
from backend.models.module import BasicModule, BasicModuleSerializer, BasicModuleViewSet
3
from backend.models.university import University
4
from rest_framework import serializers
Florent Chehab's avatar
Florent Chehab committed
5
6
7
8
9
10
11
12
13
14
15
16


def check_nones(val1, val2):
    if val1 is None and val2 is not None:
        raise serializers.ValidationError("Check your dates")

    if val2 is None and val1 is not None:
        raise serializers.ValidationError("Check your dates")

    return val1 is None and val2 is None


17
class UniversitySemestersDates(BasicModule):
Florent Chehab's avatar
Florent Chehab committed
18
19
20
21
22
23
24
25
26

    university = models.OneToOneField(
        University, on_delete=models.CASCADE, related_name='university_semesters_dates', primary_key=True, null=False)

    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)

27
28
29
    @classmethod
    def get_serializer(cls):
        return UniversitySemestersDatesSerializer
Florent Chehab's avatar
Florent Chehab committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    # Need custom validation

    # TODO add tests
    def clean(self, *args, **kwargs):
        spring_ok = check_nones(self.spring_begin, self.spring_end)
        autumn_ok = check_nones(self.autumn_begin, self.autumn_end)

        if not spring_ok:
            spring_ok = self.spring_begin < self.spring_end

        if not autumn_ok:
            autumn_ok = self.autumn_begin < self.autumn_end
        # no check if spring_end < autumn_begin in case info is not available

        if not (spring_ok and autumn_ok):
            print("ici")
            raise serializers.ValidationError("Check your dates !")
47
        super(UniversitySemestersDates, self).clean(*args, **kwargs)
Florent Chehab's avatar
Florent Chehab committed
48
49
50

    def save(self, *args, **kwargs):
        self.full_clean()
51
        super(UniversitySemestersDates, self).save(*args, **kwargs)
Florent Chehab's avatar
Florent Chehab committed
52
53


54
class UniversitySemestersDatesSerializer(BasicModuleSerializer):
Florent Chehab's avatar
Florent Chehab committed
55
56

    class Meta:
57
        model = UniversitySemestersDates
Florent Chehab's avatar
Florent Chehab committed
58
        fields = '__all__'
Florent Chehab's avatar
Florent Chehab committed
59
60


61
class UniversitySemestersDatesViewSet(BasicModuleViewSet):
62
63
    queryset = UniversitySemestersDates.objects.all()  # pylint: disable=E1101
    serializer_class = UniversitySemestersDatesSerializer