python - Django Rest Framework 在使用 ModelSerializer 保存在 View 集中之前将字段添加到模型

标签 python django serialization django-rest-framework

使用 Django Rest Framwork,我想在数据库中设置一个不能为 null 的字段,但在我实际保存模型之前,该字段不包含在 Meta 类的 fields 元组中ModelSerializer 管理。

在我的 ViewSet 中,我定义了 perform_create 并想做这样的事情:

serializer.fields.new_field = new_field_id

其中 new_field 是我模型上的外键,new_field.id 是我刚刚使用 cookie 上设置的值获取的模型的 ID。

有没有人知道一个干净的解决方案?

谢谢!

最佳答案

你是说这个..?

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

关于python - Django Rest Framework 在使用 ModelSerializer 保存在 View 集中之前将字段添加到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785030/

相关文章:

python - 将函数中的局部变量导入timeit

python - BeautifulSoup 汉字编码错误

html - 使用 Django 模板从 base.html 继承的导航栏无法正确呈现样式

php - Apache/PHP 到 Nginx/Tornado/Python

unity3d - 在 Unity 中保存和加载整个场景

python - 如何确定一组间隔是否可以覆盖低于特定成本的区域?

python - 多次调用常见的 Python 脚本

python - RuntimeError : Failed to shutdown the live test server in 2 seconds. 服务器可能卡住或生成响应缓慢。 - Django

java - ObjectOutputStream 导致内存泄漏,reset() 抛出错误

java - Jackson - 在没有自定义序列化程序的情况下更改映射键名称