Level-field validation in django rest framework 3.

2019-09-18 22:39发布

问题:

Before updating object the title field is validated. How to access data of serialized object in order to compare value with older value of this object?

from rest_framework import serializers

class BlogPostSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=100)
    content = serializers.CharField()

    def validate_title(self, value):
        """
        Check that the blog post is about Django.
        """
        if 'django' not in value.lower():
            raise serializers.ValidationError("Blog post is not about Django")
        return value

回答1:

You can do this:

def validate_title(self, value):
        """
        Check that the title has not changed.
        """
        if self.instance and value != self.instance.title
            raise serializers.ValidationError("Title of a blog post cannot be edited ")
        return value

In case of update operations, you will have access to the old object as self.instance. Then you can use that to perform your check.