scholarship.py 1.95 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
    currency = models.ForeignKey(Currency, null=True, on_delete=models.PROTECT)
20
21
    other_advantages = models.CharField(
        default='', blank=True, max_length=5000)
Florent Chehab's avatar
Florent Chehab committed
22

23
24
25
26
    frequency = models.CharField(
        max_length=1,
        choices=SCHOLARSHIP_FREQUENCIES,
        default='m',
27
28
        null=True,
        blank=True,
29
30
    )

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

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

    class Meta:
        abstract = True
47
48
49


class ScholarshipSerializer(BasicModuleSerializer):
50
    FORCE_FULL_DISPLAY = True
51

Florent Chehab's avatar
Florent Chehab committed
52
    def my_validate(self, attrs):
53
        attrs = super(ScholarshipSerializer, self).my_validate(attrs)
Florent Chehab's avatar
Florent Chehab committed
54
55
56
57
58
59
60
61
        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")
62
63
64

        return attrs

65
66
67
68
69
70
71
    class Meta:
        model = Scholarship
        fields = '__all__'


class ScholarshipViewSet(BasicModuleViewSet):
    serializer_class = ScholarshipSerializer