Skip to content

Instantly share code, notes, and snippets.

@twaddington
Created March 19, 2012 17:38
Show Gist options
  • Save twaddington/2120714 to your computer and use it in GitHub Desktop.
Save twaddington/2120714 to your computer and use it in GitHub Desktop.
# Loop over each object and either update or create.
try:
obj = MyObject.objects.get(pk=id)
obj.value1 = 1
obj.value2 = 2
except MyObject.DoesNotExist:
obj = MyObject(value1=1, value2=2, ...)
# Update the object
obj.save()
# You could also use get_or_create here:
# https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
obj, created = MyObject.objects.get_or_create(value1=1, value2=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment