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
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
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 !!'
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")
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
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
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 !!'
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")