Django Overriding Model Clean() vs Save()(Django 覆盖模型 Clean() 与 Save())
问题描述
保存模型时,我有几个操作要执行,尤其是从管理员那里.我将几个字段大写并检查以确保一个字段或另一个字段已填写.我还创建了现场蛞蝓.现在,这些在覆盖 clean 和 save 函数之间是分开的.它现在有效,但我很好奇何时使用它们.我浏览了文档,但找不到具体何时使用.
I have a couple of actions to perform when saving a models, especially from the admin. I capitalize a couple of fields and check to make sure that either one field or the other is filled. I also create the field slug. RIght now these are split between overriding the clean and the save functions. It works now, but I am curious on when to use each. I looked through the docs, and I couldn't find specifically which to use when.
推荐答案
您应该使用 clean 来完成与验证相关的工作,并解析/更改/以其他方式清理输入.大写字段和生成 slug 可能会发生在这里.我还使用 clean 将 post_type 之类的字段强制为代理模型中的特定值.如果你在 clean 中引发 django.core.exceptions.ValidationError('error text'),'error text' 会被添加到 form.non_field_errors代码>.
You should use clean to do validation-related work, and to parse/change/otherwise clean the input. Capitalizing fields and generating a slug can happen here. I also use clean to force a field like post_type to a specific value in proxy models. If you raise django.core.exceptions.ValidationError('error text') inside clean, the 'error text' is added to the form.non_field_errors.
保存是更改模型实际保存方式的地方.例如,我使用 save 来创建上传图片的裁剪.ValidationError 如果在此处提出,则不会被捕获,我觉得这是两者之间最重要的实际区别.
Save is the place to change the way a model is actually saved. For instance, I've used save to create a crop of an uploaded picture. ValidationErrors are not caught if raised here, and I feel like that's the most important practical difference between the two.
这篇关于Django 覆盖模型 Clean() 与 Save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django 覆盖模型 Clean() 与 Save()
基础教程推荐
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
