universitySemestersDates.py 1.95 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

class UniversitySemestersDatesSerializer(BasicModuleSerializer):

    def validate(self, attrs):
        spring_ok = check_nones(attrs['spring_begin'], attrs['spring_end'])
        autumn_ok = check_nones(attrs['autumn_begin'], attrs['autumn_end'])
Florent Chehab's avatar
Florent Chehab committed
37
38

        if not spring_ok:
39
            spring_ok = attrs['spring_begin'] < attrs['spring_end']
Florent Chehab's avatar
Florent Chehab committed
40
41

        if not autumn_ok:
42
            autumn_ok = attrs['autumn_begin'] < attrs['autumn_end']
Florent Chehab's avatar
Florent Chehab committed
43
44
45
        # no check if spring_end < autumn_begin in case info is not available

        if not (spring_ok and autumn_ok):
Florent Chehab's avatar
Florent Chehab committed
46
47
            raise serializers.ValidationError(
                "Check your dates !")  # TODO better error
Florent Chehab's avatar
Florent Chehab committed
48

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

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


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