fga-eps-mds/2020.2-Hortum

View on GitHub
src/hortum/customer/serializer.py

Summary

Maintainability
A
0 mins
Test Coverage
from rest_framework import serializers

from .models import Customer
from ..productor.models import Productor
from ..announcement.models import Announcement
from ..users.models import User

from ..users.serializer import UserSerializer
from ..announcement.serializer import AnnouncementListSerializer
from ..productor.serializer import ProductorListSerializer

from ..validators import ExistingValidator

class CustomerSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=True)

    class Meta:
        model = Customer
        fields = ['user', 'idAnunFav', 'idProdFav']
        read_only_fields = ['idAnunFav', 'idProdFav']

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create_user(**user_data)
        return Customer.objects.create(user=user, **validated_data)

class CustomerAddAnnouncementSerializer(serializers.ModelSerializer):
    announcementName = serializers.CharField(required=True, source='name', validators=[ExistingValidator(Announcement.objects.all())])
    email = serializers.EmailField(required=True, source='user.email', validators=[ExistingValidator(Productor.objects.all())])

    class Meta:
        model = Customer
        fields = ['email', 'announcementName']

class CustomerAddProductorSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=True, source='user.email', validators=[ExistingValidator(Productor.objects.all())])

    class Meta:
        model = Customer
        fields = ['email']

class CustomerFavoritesAnnouncementsSerializer(serializers.ModelSerializer):
    idAnunFav = AnnouncementListSerializer(many=True, read_only=True)

    class Meta:
        model = Customer
        fields = ['idAnunFav']

class CustomerFavoritesProductorsSerializer(serializers.ModelSerializer):
    idProdFav = ProductorListSerializer(many=True, read_only=True)

    class Meta:
        model = Customer
        fields = ['idProdFav']