Level-field validation in django rest framework 3.1 - access to the old value

这一生的挚爱 提交于 2019-12-24 23:30:29

问题


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.



来源:https://stackoverflow.com/questions/31089407/level-field-validation-in-django-rest-framework-3-1-access-to-the-old-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!