问题描述
保存模型时,我有几个操作要执行,尤其是从管理员那里.我将几个字段大写并检查以确保一个字段或另一个字段已填写.我还创建了现场蛞蝓.现在,这些在覆盖 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. ValidationError
s are not caught if raised here, and I feel like that's the most important practical difference between the two.
这篇关于Django 覆盖模型 Clean() 与 Save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!