Level-field validation in django rest framework 3.

2019-09-18 22:56发布

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条回答
Root(大扎)
2楼-- · 2019-09-18 23:10

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.

查看更多
登录 后发表回答