何时使用pre_save,保存,post_save在django? [英] when to use pre_save, save, post_save in django?
问题描述
我看到,当保存模型实例时,我可以覆盖或定义 pre_save,save,post_save
来执行所需的操作。
I see I can override or define pre_save, save, post_save
to do what I want when a model instance gets saved.
哪一种是首选,在哪种情况下为什么?
Which one is preferred in which situation and why?
推荐答案
我将尽力解释一个例子:
I shall try my best to explain it with an example:
pre_save
和 post_save
是信号,由...发送模型。简单来说,在模型的保存
之前或之后采取的操作将被调用。
pre_save
and post_save
are signals that are sent by the model. In simpler words, actions to take before or after the model's save
is called.
A 保存
触发以下步骤
- 发出预先保存的信号。
- 预处理数据。
- 大多数字段不进行预处理 - 现场数据保持原样。
- 准备数据库的数据。
- 将数据插入数据库。
- 发出后保存信号。
- Emit a pre-save signal.
- Pre-process the data.
- Most fields do no pre-processing — the field data is kept as-is.
- Prepare the data for the database.
- Insert the data into the database.
- Emit a post-save signal.
Django提供了一种覆盖这些信号的方法。
Django does provide a way to override these signals.
现在,
pre_save
信号可以被覆盖在实际保存到数据库之前进行一些处理 - 例子:(我不知道一个很好的例子,其中 pre_save
将是理想的在我的头顶部)
pre_save
signal can be overridden for some processing before the actual save into the database happens - Example: (I dont know a good example of where pre_save
would be ideal at the top of my head)
假设您有一个 ModelA
,它存储对 ModelB $ c的所有对象的引用$ c>其中不已被编辑。为此,您可以在
ModelB $之前注册
pre_save
信号以通知 ModelA
c $ c>的保存
方法被调用(没有什么阻止你注册一个 post_save
信号在这里)。
Lets say you have a ModelA
which stores reference to all the objects of ModelB
which have not been edited yet. For this, you can register a pre_save
signal to notify ModelA
right before ModelB
's save
method gets called (Nothing stops you from registering a post_save
signal here too).
现在,调用模型的保存
方法(不是信号) - 默认情况下,每个模型有一个保存
方法,但您可以覆盖它:
Now, save
method (it is not a signal) of the model is called - By default, every model has a save
method, but you can override it:
class ModelB(models.Model):
def save(self):
#do some custom processing here: Example: convert Image resolution to a normalized value
super(ModelB, self).save()
然后,您可以注册 post_save
(这更常用于 pre_save
)
Then, you can register the post_save
signal (This is more used that pre_save
)
一个常见的用例是 UserProfile
对象创建时,用户
对象在系统中创建。
A common usecase is UserProfile
object creation when User
object is created in the system.
您可以注册一个 post_save
信号,它创建一个对应于每个用户
的 UserProfile
系统。
You can register a post_save
signal which creates a UserProfile
object that corresponds to every User
in the system.
信号是保持模块化和显式化的一种方式。 (显式通知 ModelA
如果我保存
或更改 ModelB
)
Signals are a way to keep things modular, and explicit. (Explicitly notify ModelA
if i save
or change something in ModelB
)
我会想到更具体的现实世界的例子,试图更好地回答这个问题。与此同时,我希望这可以帮助你
I shall think of more concrete realworld examples in an attempt to answer this question better. In the meanwhile, I hope this helps you
这篇关于何时使用pre_save,保存,post_save在django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!