如何在DRF中使字段可编辑= False

时间:2018-10-07 07:00:32

标签: python django django-rest-framework

我有一个序列化器。我想限制更新字段。我该怎么办?

Dim points As Variant
Dim sh As Shape

points = Array(Array(10.5, 10.5), Array(20.4, 20.4), Array(5.1, 30.3), Array(10.5, 10.5))

' These both do not work and I get error about wrong type (error 1004) in 2007
' and application defined error 1004 on 2010:

ActiveWorkbook.ActiveSheet.Shapes.AddPolyline points
Set sh = ActiveWorkbook.ActiveSheet.Shapes.AddPolyline(points)

' These work fine:

ActiveWorkbook.ActiveSheet.Shapes.AddPolyline (points)
Set sh = ActiveWorkbook.ActiveSheet.Shapes.AddPolyline((points))

class ABCSerializer(serializers.ModelSerializer): class Meta: """Meta.""" model = ModelA fields = ('colA', 'colB', 'colC',) 是创建对象时的必填字段。但是,不应允许对其进行更新。我该怎么办?

4 个答案:

答案 0 :(得分:1)

听起来像PUTPOST方法需要不同的序列化器。在PUT方法的序列化器中,您可以将colA字段设置为readonly

class ABCViewSet(ModelViewSet):
    serializer_class = ABCSerializer

    def get_serializer_class(self):
        serializer_class = self.serializer_class
        if self.request.method == 'PUT':
            serializer_class = SerializerWithReadOnlyColA
        return serializer_class

答案 1 :(得分:1)

您可以使用Django REST框架field-level validation,方法是验证该字段在更新时是否保持不变,如下所示:

from rest_framework.exceptions import ValidationError

class ABCSerializer(serializers.ModelSerializer):
    colA = serializers.CharField(max_length=100)

    def validate_colA(self, value):
        if self.instance and self.instance.colA != value:
            raise ValidationError("You may not edit colA")
        return value

    class Meta:
        """Meta."""

        model = ModelA
        fields = ('colA', 'colB', 'colC',)

这将检查这是否是一个更新(通过检查实例是否已在序列化器上填充),如果是,则它将检查是否对字段进行了更改,是否将其抛出ValidationError。这种方法的好处是,您可以将视图代码保持与以前相同,并继续在序列化程序中保持验证行为。

答案 2 :(得分:0)

您可以覆盖序列化程序的update方法,以仅更新所需的字段。

class ABCSerializer(serializers.ModelSerializer):
    def update(self, instance, validated_data):
        instance.colB = validated_data.get('colB', instance.colB)
        instance.colC = validated_data.get('colC', instance.colC)
        # do nothing to instance.colA
        instance.save()
        return instance

    class Meta:
        model = ModelA
        fields = ('colA', 'colB', 'colC',)

或者,如果您有很多字段,并且只想省略更新colA,则可以这样编写update方法:

def update(self, instance, validated_data):
    validated_data.pop('colA') # validated_data no longer has colA
    return super().update(instance, validated_data)

您可以在此处阅读有关覆盖update的更多信息:https://www.django-rest-framework.org/api-guide/serializers/#saving-instances

答案 3 :(得分:-1)

您可以使用read_only_fields选项

class ABCSerializer(serializers.ModelSerializer):
    class Meta:
        """Meta."""

        model = ModelA
        fields = ('colB', 'colC',)
        read_only_fields = ('colA',)