Django覆盖模型Clean

Django覆盖模型Clean

本文介绍了Django覆盖模型Clean()vs 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进行验证相关的工作,并解析/更改/否则清除输入。在此处可能会发生资本化字段并产生子弹的情况。我还使用clean强制将 post_type 之类的字段设置为代理模型中的特定值。如果在干净的内部引发 django.core.exceptions.ValidationError('错误文本'),则'错误文本'被添加到 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.

保存是更改模型实际保存方式的地方。例如,我使用保存创建了一批上传的图片。如果在这里引发 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()vs Save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:46