Thursday, 28 December 2023

django how to use serializer to validate, and difference between serializer.data nd validated_data

https://stackoverflow.com/questions/42000687/what-are-the-differences-between-data-and-validated-data

// Use serializer to validate
class UserSerializer(serializers.Serializer):
    name = serializers.CharField()
    phone = serializers.CharField(required=False, allow_null=True)

>>> user = UserSerializer(data={'name': 'Foo'})
>>> user.is_valid()
True
>>> user.data
{'name': 'Foo', 'phone': None}
>>> user.validated_data
{'name': 'Foo'}
# Note in this case data and validated_data are not the same, since phone is None and 
allowed it does not show up in validated_data, use validated_data is recommended

https://www.django-rest-framework.org/api-guide/serializers/

When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example:

serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
serializer.is_valid()


asdas




No comments:

Post a Comment