什么时候在 Django 中使用 pre_save、save、post_save? [英] when to use pre_save, save, post_save in django?

查看:28
本文介绍了什么时候在 Django 中使用 pre_save、save、post_save?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到我可以覆盖或定义 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_savepost_save信号 由模型发送.简而言之,在调用模型的 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 save 触发以下步骤

  • 发出预存信号.
  • 预处理数据.
  • 大多数字段不进行预处理 - 字段数据保持原样.
  • 为数据库准备数据.
  • 将数据插入到数据库中.
  • 发出保存后信号.

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 的所有对象的引用,这些对象还被编辑.为此,您可以在 ModelBsave 方法被调用之前注册一个 pre_save 信号以通知 ModelA(没有什么可以阻止您在此处注册 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).

现在,调用模型的 save 方法(它不是信号) - 默认情况下,每个模型都有一个 save 方法,但您可以覆盖它:

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)

一个常见的用例是在系统中创建 User 对象时创建 UserProfile 对象.

A common usecase is UserProfile object creation when User object is created in the system.

您可以注册一个 post_save 信号,该信号创建一个 UserProfile 对象,该对象对应于系统中的每个 User.

You can register a post_save signal which creates a UserProfile object that corresponds to every User in the system.

信号是一种保持模块化和明确的方式.(如果我 save 或更改 ModelB 中的某些内容,则显式通知 ModelA )

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

这篇关于什么时候在 Django 中使用 pre_save、save、post_save?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆