[Fixed]-Django โ€“ post_init signal is called on Model instance save & before instance is even created. Why?

24๐Ÿ‘

โœ…

You seem to have a bit of confusion over what it means to instantiate an object. It has nothing whatever to do with the database. This instantiates a model object without saving it to the database, in which case its pk will be None:

MyObject(field1='foo', field2='bar')

and this (indirectly) instantiates an object by getting it from the database:

MyObject.objects.get(field1='baz')

The post_init signal will be sent in both of these cases, even though neither of them has anything to do with saving to the database.

If you want something to happen when you save, either override the save method itself, or use the pre_save or post_save signals. You can check there whether or not the object has been previously saved, by verifying if its pk is None.

๐Ÿ‘คDaniel Roseman

2๐Ÿ‘

I know the question is old but I had a similar problem and easy solution for that is just using post_save signal and check if created

@receiver(post_save, sender=YourSender) 
   def when_init(sender, instance, created, **kwargs):
      if created:
         ...
๐Ÿ‘คbazzuk123

Leave a comment