Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post_save in django to update instance immediately

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?

like image 479
givp Avatar asked Oct 28 '09 23:10

givp


People also ask

What is pre save signal in django?

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.

What is Post_save in Django?

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.

When to use django signals?

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.

Does Django update call save?

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.


1 Answers

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)
like image 133
ozan Avatar answered Oct 12 '22 12:10

ozan