scholarship.py 1.89 KB
Newer Older
1
from django.db import models
2
from backend.models.abstract.basic_module import BasicModule, BasicModuleSerializer, BasicModuleViewSet
3
from backend.models.currency import Currency
4
from rest_framework import serializers
5
6
from django.core.validators import MinValueValidator

7
8
9
10
11
12
13
14
SCHOLARSHIP_FREQUENCIES = (
    ('w', 'week'),
    ('m', 'month'),
    ('s', 'semester'),
    ('y', 'year'),
    ('o', 'one_shot')
)

15
16
17

class Scholarship(BasicModule):

Florent Chehab's avatar
Florent Chehab committed
18
    type = models.CharField(max_length=200)
Florent Chehab's avatar
Florent Chehab committed
19
20
21
    currency = models.ForeignKey(Currency, null=True, on_delete=models.PROTECT)
    other_advantages = models.TextField(blank=True, default="")

22
23
24
25
26
27
    frequency = models.CharField(
        max_length=1,
        choices=SCHOLARSHIP_FREQUENCIES,
        default='m',
    )

28
    amount_min = models.DecimalField(
Florent Chehab's avatar
Florent Chehab committed
29
        null=True,
30
31
32
33
34
35
        max_digits=20,
        decimal_places=2,
        validators=[MinValueValidator(0)]
    )

    amount_max = models.DecimalField(
Florent Chehab's avatar
Florent Chehab committed
36
        null=True,
37
38
39
40
41
42
43
        max_digits=20,
        decimal_places=2,
        validators=[MinValueValidator(0)]
    )

    class Meta:
        abstract = True
44
45
46


class ScholarshipSerializer(BasicModuleSerializer):
47
    FORCE_FULL_DISPLAY = True
48

Florent Chehab's avatar
Florent Chehab committed
49
    def my_validate(self, attrs):
50
        attrs = super(ScholarshipSerializer, self).my_validate(attrs)
Florent Chehab's avatar
Florent Chehab committed
51
52
53
54
55
56
57
58
        if attrs['amount_min'] is not None:
            if attrs['currency'] is None:
                raise serializers.ValidationError(
                    "A currency must be specified when there is a value")
            if attrs['amount_max'] is not None:
                if attrs['amount_max'] < attrs['amount_min']:
                    raise serializers.ValidationError(
                        "amount_max should be greater or equal than amount_min")
59
60
61

        return attrs

62
63
64
65
66
67
68
    class Meta:
        model = Scholarship
        fields = '__all__'


class ScholarshipViewSet(BasicModuleViewSet):
    serializer_class = ScholarshipSerializer