Sorry for some crazy subj.
I'd like to override django models save method and call some additional code if the model instance is newly created. Sure I can use signals or check if the model have empty pk field and if yes, create temporary variable and late开发者_运维百科r call a code:
Class EmailModel(models.Model):
email = models.EmailField()
def save(self, *args, **kwargs)
is_new = self.pk is None
super(EmailModel, self).save(*args, **kwargs)
# Create necessary objects
if is_new:
self.post_create()
def post_create(self):
# do job, send mails
pass
But I like to have some beautiful code and avoid using temporary variable in save method. So the question is: is it possible to find if the instance of model is newly created object just after super save_base parent method call?
I've checked django sources can't find how to do that in right way.
Thanks
We have related post
For real - signals are best approch in this case.
You could use post_save()
signal and in the listener just check if the credit_set exist for current model instance and if not - create one. That would be my choice - there is no need to overdo such a simple task.
Of course if you really need to know exactly when the model was initiated (I doubt it) use post_init()
signal. You don't need to override save() method just to set some additional variables. Just catch post_init()
signal, or pre_save()
, and just change/add what you want. IMHO there is no sense to override save()
method and check if this is new instance or not - that's why the signals are there.
精彩评论