简体   繁体   中英

drf ModelSerializer field level validation

I'm trying to Field-Level validation to validate branch field in ModelSerialzer but this method never called.

class UserProfileSerializer(serializers.ModelSerializer):
    branch = serializers.ChoiceField(choices=Branch.choices)

    class Meta:
        model = UserProfile
        exclude = ['user']

    def validate_branch(self, branch):
        print(branch)
        return branch.upper()


class CustomRegisterSerializer(RegisterSerializer):
    profile = UserProfileSerializer(source="userprofile")

    @transaction.atomic
    def create(self, validated_data):
        validated_profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        UserProfile.objects.create(user=user, **validated_profile_data)
        return user

I followed this drf docs .

The validators are run when is_valid is called. You can get some idea from the code mentioned below on how to call the is_valid() method. You can call it from views.py.

serializer = UserProfileSerializer(data="The data you want to send")
serializer.is_valid(raise_exception=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM