zhuyxn zhuyxn - 1 year ago 114
Python Question

Django: Calling .update() on a single model instance retrieved by .get()?

Have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects. If it returns 0, I create a new model instance in the

except DoesNotExist
clause of the function. Otherwise, I would like to update the fields in the pre-existing instance, without creating a new one. I was originally attempting to call
on the instance which was found, but
seems to be only callable on a QuerySets. How do I get around changing a dozen fields, without calling .filter() and comparing the lengths to know if I have to create or update a pre-existing instance?

Answer Source

With the advent of Django 1.7, there is now a new update_or_create QuerySet method which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level.

Example from the documentation:

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon', defaults=updated_values)

Pre-Django 1.7:

Change the model field values as appropriate, then call .save() to persist the changes:

    obj = Model.objects.get(field=value)
    obj.field = new_value
except Model.DoesNotExist:
    obj = Model.objects.create(field=new_value)
# do something else with obj if need be
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download