wasimbhalli
wasimbhalli

Reputation: 5242

When is the "post_save" signal in django activated/called?

I've to update some database tables after saving a particular model. I've used the @receiver(post_save decorator for this. But when in this decorator function, the values are still not saved in the database. I've one to many relation but when I get the current instance that is being saved using kwargs['instance'], it doesn't have child objects. But after saving when I check from shell, it does have child objects. Following is the code that I'm using:

@receiver(post_save, sender=Test)
def do_something(sender, **kwargs):
    test = kwargs['instance']
    users = User.objects.filter(tags__in=test.tags.values_list('id',flat=True))
    for user in users:
        other_model = OtherModel(user=user, test=test, is_new=True)
        other_model.save()

Upvotes: 3

Views: 1678

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

post_save is sent at the end of Model.save_base(), which is itself called by Model.save((). This means that if you override your model's save() method, post_save is sent when you call on super(YourModel, self).save(*args, **kw).

If Tag has a ForeignKey on Test and the Test instance was just created, you can't expect to have any Tag instance related to your Test instance at this stage, since the Tag instances obviously need to know the Test instance's pk first so they can be saved too.

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599630

The post_save for the parent instance is called when the parent instance is saved. If the children are added after that, then they won't exist at the time the parent post_save is called.

Upvotes: 0

Related Questions