У меня есть следующий код в моем client/serializer.py
, и я не знаю, является ли хорошей практикой выполнение проверки / проверки моих моделей в сериализаторах методов.Это хорошая практика?
from rest_framework import serializers, exceptions
from .models import Staff
from django.contrib.auth import get_user_model
from profession.models import Profession
from django.db import IntegrityError
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=24, min_length=4, allow_blank=False, trim_whitespace=True)
first_name = serializers.CharField(max_length=100, min_length=1, allow_blank=False, trim_whitespace=True)
last_name = serializers.CharField(max_length=100, min_length=1, allow_blank=False, trim_whitespace=True)
email = serializers.EmailField()
class ProfessionSerializer(serializers.Serializer):
url = serializers.URLField(read_only=True)
id = serializers.IntegerField()
name = serializers.CharField(read_only=True)
class StaffSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
profession = ProfessionSerializer()
class Meta:
model = Staff
fields = ['url', 'id', 'commission', 'user', 'profession']
def create(self, validated_data):
user_data = validated_data.pop('user')
profession_data = validated_data.pop('profession')
try:
profession = Profession.objects.get(pk=profession_data.get('id'))
except Profession.DoesNotExist:
raise exceptions.ValidationError({'profession': ['profession with this id does not exists.']})
try:
user = get_user_model().objects.create(**user_data)
except IntegrityError:
raise exceptions.ValidationError({'user': ['user with this username already exists.']})
staff = Staff.objects.create(user=user, profession=profession, **validated_data)
return staff