首页 > 解决方案 > Django Rest Framework:按 id 创建/更新,输出字典

问题描述

我有一个 django-rest-framework 模型视图集(用于测试),它使用这样的序列化:

class ProcessSerializer(serializers.Serializer):
    class Meta:
        model = Process.draft_model
        fields = ['id', 'name']


class TestSerializer(serializers.ModelSerializer):
    process = ProcessSerializer()

    class Meta:
        model = ConfigurationTest
        fields = [
            'id',
            'name',
            'process',
        ]

这在检索测试时效果很好,但不适用于创建/更新,理想情况下我希望只向 ID 提供这样的请求:

{
  process: 1
  name: 'A new test'
}

将该请求发送到服务器时,我收到一个错误,例如Invalid data. Expected a dictionary, but got int

我尝试了什么:

参考型号

class ConfigurationTest(...):
    name = CharField(max_length=120)
    process = ForeignKey(Process)

class Process(...):
    name = CharField(max_length=120)

标签: pythondjango-rest-framework

解决方案


我会给一个这样的序列化程序。read_only 的一个序列化器字段,它使用 ProcessSerializer 和 process_id 的 write_only 作为整数。

class TestSerializer(serializers.ModelSerializer):
    process = ProcessSerializer(read_only=True)
    process_id = IntegerField(write_only=True)

    class Meta:
        model = ConfigurationTest
        fields = [
            'id',
            'name',
            'process',
            'process_id',
        ]
 

并发布:

{
  process_id: 1
  name: 'A new test'
}

我不是 100% 确定您不需要覆盖创建/更新,但这应该可以正常工作。

注意:我看到你尝试了类似逻辑的东西。虽然是相同的代码吗?


推荐阅读