[Fixed]-Post_save in django to update instance immediately


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)


Doesn’t the post_save handler take the instance? Why are you filtering using it? Why not just do:

def my_handler(sender, instance=False, created, **kwargs):
  if created:
     instance.blah = 'hello'

Your existing code doesn’t work because it loops, and Test.objects.filter(id=instance.id) returns a query set, not an object. To get a single object directly, use Queryset.get(). But you don’t need to do that here. The created argument keeps it from looping, as it only sets it the first time.

In general, unless you absolutely need to be using post_save signals, you should be overriding your object’s save() method anyway.

Leave a comment