django rest framework:限制可以更新的字段

时间:2015-09-18 11:00:15

标签: django django-rest-framework

我希望用户只能更新一个特定字段。例如:

models.py

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    class Meta:
        ordering = ('created',)

serializer.py

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

views.py

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

创建Snippet后,用户应该只能更新title字段。

我知道我可以通过以下方式实现这一目标:

serializers.py

def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.save()
        return instance

在序列化程序类中。但我想知道,有可能浏览api只能在编辑表单中显示title字段吗?并且还跳过不需要的字段的验证?

2 个答案:

答案 0 :(得分:8)

Django REST Framework提供read_onlywrite_only属性,用于控制用于编辑的内容和不用于编辑的内容。

serializers.py

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
        extra_kwargs = {
            'id': {'read_only': True},
            'code': {'read_only': True},
            'lineos': {'read_only': True},
            'language': {'read_only': True},
            'style': {'read_only': True}
        }

以上将返回读取请求的所有字段,但只有标题可写。 您可以在官方文档中找到更多信息: http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields

答案 1 :(得分:0)

此代码将更新请求中发送的参数将更新。

views.py

UrlHelper