scholarship.py 2.1 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.core.validators import MinValueValidator
2
from django.db import models
Florent Chehab's avatar
Florent Chehab committed
3

4
5
6
7
8
from backend_app.models.abstract.basic_module import (
    BasicModule,
    BasicModuleSerializer,
    BasicModuleViewSet,
)
Florent Chehab's avatar
Florent Chehab committed
9
from backend_app.models.currency import Currency
10
from rest_framework import serializers
11

12
SCHOLARSHIP_FREQUENCIES = (
13
14
15
16
17
    ("w", "week"),
    ("m", "month"),
    ("s", "semester"),
    ("y", "year"),
    ("o", "one_shot"),
18
19
)

20
21

class Scholarship(BasicModule):
Florent Chehab's avatar
Florent Chehab committed
22
23
24
    """
    Abstract model for scholarships
    """
25

Florent Chehab's avatar
Florent Chehab committed
26
    short_description = models.CharField(max_length=200)
Florent Chehab's avatar
Florent Chehab committed
27
    currency = models.ForeignKey(Currency, null=True, on_delete=models.PROTECT)
28
    other_advantages = models.CharField(default="", blank=True, max_length=5000)
Florent Chehab's avatar
Florent Chehab committed
29

30
31
32
    frequency = models.CharField(
        max_length=1,
        choices=SCHOLARSHIP_FREQUENCIES,
33
        default="m",
34
35
        null=True,
        blank=True,
36
37
    )

38
    amount_min = models.DecimalField(
39
        null=True, max_digits=20, decimal_places=2, validators=[MinValueValidator(0)]
40
41
42
    )

    amount_max = models.DecimalField(
43
        null=True, max_digits=20, decimal_places=2, validators=[MinValueValidator(0)]
44
45
46
47
    )

    class Meta:
        abstract = True
48
49
50


class ScholarshipSerializer(BasicModuleSerializer):
Florent Chehab's avatar
Florent Chehab committed
51
52
53
54
    """
    Serializer for the scholarship class
    """

55
    def validate(self, attrs):
Florent Chehab's avatar
Florent Chehab committed
56
57
58
        """
        Custom attribute validation
        """
59
60
61

        attrs = super().validate(attrs)

62
63
        if attrs["amount_min"] is not None:
            if attrs["currency"] is None:
Florent Chehab's avatar
Florent Chehab committed
64
                raise serializers.ValidationError(
65
66
                    "A currency must be specified when there is a value"
                )
Florent Chehab's avatar
Florent Chehab committed
67
68
69
70
71
72
73
            if (
                attrs["amount_max"] is not None
                and attrs["amount_max"] < attrs["amount_min"]
            ):
                raise serializers.ValidationError(
                    "amount_max should be greater or equal than amount_min"
                )
74
75
76

        return attrs

77
78
    class Meta:
        model = Scholarship
79
        fields = "__all__"
80
81
82
83


class ScholarshipViewSet(BasicModuleViewSet):
    serializer_class = ScholarshipSerializer