首页 > 解决方案 > 首先是什么:视图或序列化程序?

问题描述

最近我遇到了嵌套对象发布的问题。在研究了涉及视图 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:在请求之后首先调用什么:序列化程序或视图?

标签: postdjango-rest-frameworkdjango-viewsaxiosdjango-serializer

解决方案


您可以在序列化程序中使用SlugRelatedField

file = serializers.SlugRelatedField(
        slug_field='name'
     )

但是您的模型的名称字段应该是唯一的=True


推荐阅读