Skip to content

Instantly share code, notes, and snippets.

@kidsil
Created May 27, 2013 19:20
Show Gist options
  • Save kidsil/5658666 to your computer and use it in GitHub Desktop.
Save kidsil/5658666 to your computer and use it in GitHub Desktop.
load in case of duplicate unique
#Problem is, if I had a unique field, and I'd get an error when trying to save a new object that was conflicting with it,
#I wanted the object to load automatically in case it already exists
#So I wrote a custom save function (which returns the ID in case the object already exists)
def save(self, *args, **kwargs):
try:
super(Place, self).save(*args, **kwargs)
except IntegrityError, e:
existing_object = Place.objects.get(slug=self.slug)
self = existing_object #this doesn't really work for some reason..
super(Place, self).save(*args, **kwargs)
return existing_object.id #this is necessary otherwise the_object doesn't have an ID
#when saving:
the_id = the_object.save()
if the_id:
the_object.id = the_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment