Django pre_save signal: how do I know if it is Insert or Update

Question:

I’m working in a pre_save signal of a model and I don’t know how to check if the record is a INSERT or UPDATE. Code below (doesn’t work properly):

@receiver(pre_save, sender=Person)
def pre_save_person(sender, instance, **kwargs): 

    if not instance.pk:
        print 'INSERT !!!!!!'
    else:
        print 'UPDATE !!!!!!'

Can you help me? The project uses django 1.8.7.

Thanks for any help

Asked By: André Luiz

||

Answers:

Try with

if instance.pk is None:
print "inserting"
else:
print "updating"

this wont work in all cases , I recommend using post_save where you have the flag created unless you specifically need pre_save

Answered By: Radhouane Fazai

Following @ knbk comment, the instance.pk will always exist at this point. You must check if this instance.pk exists in database:

@receiver(pre_save, sender=Person)
def pre_save_person(sender, instance, **kwargs):

    num = Person.objects.filter(pk=instance.pk).count()
    if num == 0 :
        print 'INSERT !!'
    else:
        print 'UPDATE !!'
Answered By: André Luiz

You can check it in a simple way

@receiver(pre_save, sender=Person)
def pre_save_person(sender, instance, **kwargs): 
    try:
        Person.objects.get(pk=instance.pk)
        print("inserting")
    except Person.DoesNotExist:
        print("updating")
Answered By: Benzion.R
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.