python - 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
我尝试了什么:
- 拥有
process
和process_id
作为包含的字段,并且只是发送process_id
一个 POST 请求。在这种情况下,我会收到类似的错误process_id cannot be null
,这很容易混淆。 - 对操作使用不同的序列化程序
create
,它process
用作没有嵌套序列化程序的普通 PrimaryKeyRelatedField。这对于获取请求非常有效,但显然也意味着服务器对该 POST 请求的响应不包括嵌套良好的序列化程序。
参考型号
class ConfigurationTest(...):
name = CharField(max_length=120)
process = ForeignKey(Process)
class Process(...):
name = CharField(max_length=120)
解决方案
我会给一个这样的序列化程序。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% 确定您不需要覆盖创建/更新,但这应该可以正常工作。
注意:我看到你尝试了类似逻辑的东西。虽然是相同的代码吗?
推荐阅读
- android - 项目重建失败,但 APK 编译并正确运行
- python - Google Cloud 函数 Python Flask 模板文件夹
- javascript - 初始化时 Owl-Carousel 超大图像
- image - 图像停止响应作为元素的子元素
- rest - 注入所有 GERRIT 环境变量,就好像 Jenkins 作业是由 gerrit 事件启动一样
- java - 扫描器输入的子串
- php - 如何在mysql中创建一个双id字段?还是这样的?
- swift - 组合 NSManagedObject 类
- javascript - 将 select 及其选项转换为 div
- reactjs - React-Native:如何a)清除文本输入或b)禁止显示输入的文本