The Python Oracle

Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist?

This video explains
Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Question
01:15 Accepted answer (Score 25)
01:40 Answer 2 (Score 60)
01:59 Answer 3 (Score 22)
02:32 Answer 4 (Score 11)
02:56 Thank you

--

Full question
https://stackoverflow.com/questions/3607...

Accepted answer links:
[documentation]: http://docs.djangoproject.com/en/dev/ref...
[does]: http://docs.djangoproject.com/en/dev/ref...
[version 1.0]: http://docs.djangoproject.com/en/1.0/ref...

Answer 3 links:
[Django : What is the role of ModelState?]: https://stackoverflow.com/questions/1156...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #keywordargument

#avk47



ANSWER 1

Score 70


Primary key attribute usually assigned by the database when the instance saved first time. So you can use something like if instance.pk is None




ACCEPTED ANSWER

Score 31


According to the latest Django documentation, pre_save does NOT send a created argument. Post_save however does. I could not find any reference of the signal sending created since version 1.0.




ANSWER 3

Score 27


I am not sure if this is the recommended way but @Radagast's method didnt work for me(not sure if its because I use custom Pk's).

I tried the following(not sure if this is the best way):

@receiver(pre_save, sender=YourModelName, weak=False, )
def presave_payment_model_check(sender, instance=None, created=False, **kwargs):
    #Reference: https://stackoverflow.com/questions/11561722/django-what-is-the-role-of-modelstate
    if instance._state.adding:
        # we would need to create the object
        print "Creating an object"
    else:
        #we are updating the object
        print "Updating an object"
    

Reference: Django : What is the role of ModelState?




ANSWER 4

Score 4


Using instance._state.adding is the most logical approach, as you will be able to tell the model state exists or is new, regardless whether the primary key as been assigned or not.