post - 首先是什么:视图或序列化程序?
问题描述
最近我遇到了嵌套对象发布的问题。在研究了涉及视图 create() 实现或用于读取和写入的单独序列化程序的正确解决方案后,重写了 create() 方法。
我使用 axios 发布,我的对象如下所示:
{
comment: str
priority: str
file: int // -> this one is ForeignKey for another object and needs its PK which is ID
}
我想让我的帖子数据结构化的方式是:
{
comment: str
priority: str
file: str // -> which is file object name
}
发送此请求后,DRF 应在 db 中查找有关此名称的文件,并将其 id 放在此文件中。
这是正确的方法吗?或者我应该嵌套整个对象而不仅仅是它的 id ?
另一个问题,offtopic:在请求之后首先调用什么:序列化程序或视图?
解决方案
您可以在序列化程序中使用SlugRelatedField
file = serializers.SlugRelatedField(
slug_field='name'
)
但是您的模型的名称字段应该是唯一的=True
推荐阅读
- firebase - 如何从 Firebase 身份验证更改电子邮件的电子邮件发件人姓名?
- angular - 回调按钮时角度删除查询参数
- javascript - 反应本机(博览会)网络视图错误 net::ERR_CACHE_MISS
- php - DiscriminatorMap 注解中的环境变量或函数
- laravel - Api Endpoint 中不存在 Authorizarion 标头 - Laravel
- javascript - 如何使最小填充图表js折线图
- angular - 从 Angular 8 应用程序向身份验证 API 端点发出请求会导致 CORS 错误,而来自 Postman 的相同请求可以完美运行文件
- laravel - .env 文件中的 MySQL 密码不起作用,但在 database.php 中工作正常(env() 缓存旧密码,config:clear 不会删除它)
- mysql-8.0 - MySQLSyntaxErrorException:升级时您的 SQL 语法有错误
- jquery - 如何在jQuery中声明和初始化变量