Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

python - when to use pre_save, save, post_save in django?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I shall try my best to explain it with an example:

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 triggers the following steps

  • 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 does provide a way to override these signals.

Now,

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)

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()

Then, you can register the post_save signal (This is more used that pre_save)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...