Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

django rest framework serializers

#
class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()
    def create(self, validated_data):
        return Comment.objects.create(**validated_data)
		# or return Comment(**validated_data)

    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.content = validated_data.get('content', instance.content)
        instance.created = validated_data.get('created', instance.created)
        instance.save()
        return instance
#Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:
# .save() will create a new instance.
serializer = CommentSerializer(data=data)

# .save() will update the existing `comment` instance.
serializer = CommentSerializer(comment, data=data)


#serializer errors
from rest_framework import serializers
if --- :
  raise serializers.ValidationError("Blog post is not about Django")

 
PREVIOUS NEXT
Tagged: #django #rest #framework #serializers
ADD COMMENT
Topic
Name
5+6 =