from django.core.validators import MinValueValidator from django.db import models from backend_app.models.abstract.module import Module, ModuleSerializer, ModuleViewSet from backend_app.models.currency import Currency from rest_framework import serializers SCHOLARSHIP_FREQUENCIES = ( ("w", "week"), ("m", "month"), ("s", "semester"), ("y", "year"), ("o", "one_shot"), ) class Scholarship(Module): """ Abstract model for scholarships """ short_description = models.CharField(max_length=200) currency = models.ForeignKey(Currency, null=True, on_delete=models.PROTECT) other_advantages = models.CharField(default="", blank=True, max_length=5000) frequency = models.CharField( max_length=1, choices=SCHOLARSHIP_FREQUENCIES, default="m", null=True, blank=True, ) amount_min = models.DecimalField( null=True, max_digits=20, decimal_places=2, validators=[MinValueValidator(0)] ) amount_max = models.DecimalField( null=True, max_digits=20, decimal_places=2, validators=[MinValueValidator(0)] ) class Meta: abstract = True class ScholarshipSerializer(ModuleSerializer): """ Serializer for the scholarship class """ def validate(self, attrs): """ Custom attribute validation """ attrs = super().validate(attrs) 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 and attrs["amount_max"] < attrs["amount_min"] ): raise serializers.ValidationError( "amount_max should be greater or equal than amount_min" ) return attrs class Meta: model = Scholarship fields = "__all__" class ScholarshipViewSet(ModuleViewSet): serializer_class = ScholarshipSerializer