Django 无法使用序列化程序更新字段

Django not able to update field with serialzier

嗨,我有这样的序列化器

class PredefinedHabitSerializer(serializers.ModelSerializer):

    image= serializers.SerializerMethodField()

    class Meta:
        model = models.PredefinedHabit
        fields = [
            "id",
            "habit",
            "category",
            "why",
            "how",
            "dos",
            "donts",
            "info",
            "alternative",
            "image"
        ]

    def get_image(self, obj):
        if  obj.image.startswith("https"):
            return obj.image
        else:
            return aws_get(obj,"s3-debug")

我的序列化程序get_image方法用于获取存储在模型字段image

中的图像密钥的预签名URL

以及编辑此模型的视图

def edit_predefined_habit(request):
        predefined_habit = PredefinedHabit.objects.get(id=request.data.get("id"))
        data = {
            "category": request.data.get("category"),
            "habit": request.data.get("habit"),
            "why": request.data.get("why"),
            "how": request.data.get("how"),
            "dos": request.data.get("dos"),
            "donts": request.data.get("donts"),
            "info": request.data.get("info"),
            "alternative": request.data.get("alternative"),
            "image": request.data.get("illustration"),
        }
        data = Functions.clean(data)
        serializer = PredefinedHabitSerializer(predefined_habit, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(data={"status": "success"})

查看获取所有对象

def viewPredefinedHabits(request):
        model = PredefinedHabit.objects.all()
        serializer = PredefinedHabitSerializer(model, many=True)
        return Response(serializer.data)

我无法通过编辑 API 更新我的图像字段,据我所知,这是因为我已将图像指定为序列化程序方法字段。我该如何克服这个问题?我试过了write_only 不行

我能想到的其他方法是手动保存到对象中并保存而不传递给序列化程序。

您可以为每种请求类型构建序列化程序。

class PredefinedHabitReadSerializer(serializers.ModelSerializer):

    image= serializers.SerializerMethodField()

    class Meta:
        model = models.PredefinedHabit
        fields = [
            "id",
            "habit",
            "category",
            "why",
            "how",
            "dos",
            "donts",
            "info",
            "alternative",
            "image"
        ]

    def get_image(self, obj):
        if  obj.image.startswith("https"):
            return obj.image
        else:
            return aws_get(obj,"s3-debug")

class PredefinedHabitUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.PredefinedHabit
        fields = [
            "habit",
            "category",
            "why",
            "how",
            "dos",
            "donts",
            "info",
            "alternative",
            "image"
        ]
    def to_representation(self, instance):
        return PredefinedHabitReadSerializer(instance).data

当您需要更新模型实例时可以使用 PredefinedHabitUpdateSerializer。如果您需要检索或列出您的查询,您可以使用 PredefinedHabitReadSerializer.