I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record:
def my_handler(sender, instance=False, **kwargs):
t = Test.objects.filter(id=instance.id)
t.blah = 'hello'
t.save()
class Test(models.Model):
title = models.CharField('title', max_length=200)
blah = models.CharField('blah', max_length=200)
post_save.connect(my_handler, sender=Test)
So the 'extra' field is supposed to be set to 'hello' after each save. Correct? But it's not working.
Any ideas?
pre_save) is provoked just before the model save() method is called, or you could say model save method is called only after pre_save is called and done its job free of errors.
Post-save SignalThe post_save logic is just a normal function, the receiver function, but it's connected to a sender, which is the Order model. The code block below demonstrates the sample receiver function as a post-save. 1from django. db. models.
You can use Django Signals when you want to run a specific code before or after the event on the model/database. For example when you update user then it should also update the profile model instance using the django post_save method.
Saving a Django model object updates all your columns every single time you call a save() method. To prevent this from happening you must be explicit.
When you find yourself using a post_save signal to update an object of the sender class, chances are you should be overriding the save method instead. In your case, the model definition would look like:
class Test(models.Model):
title = models.CharField('title', max_length=200)
blah = models.CharField('blah', max_length=200)
def save(self, force_insert=False, force_update=False):
if not self.blah:
self.blah = 'hello'
super(Test, self).save(force_insert, force_update)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With