[英]drf ModelSerializer field level validation
I'm trying to Field-Level validation to validate branch
field in ModelSerialzer but this method never called.我正在尝试进行字段级验证以验证 ModelSerialzer 中的
branch
字段,但从未调用过此方法。
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
The validators are run when is_valid is called.调用 is_valid 时运行验证器。 You can get some idea from the code mentioned below on how to call the is_valid() method.
您可以从下面提到的代码中了解如何调用 is_valid() 方法。 You can call it from views.py.
您可以从views.py 中调用它。
serializer = UserProfileSerializer(data="The data you want to send")
serializer.is_valid(raise_exception=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.