Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I 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 .update() on the instance which was found, but .update() 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?

like image 331
zhuyxn Avatar asked Sep 12 '12 05:09

zhuyxn


People also ask

How do I update a field in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

What is __ GTE in Django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value.

What is __ Str__ in Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


2 Answers

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={'first_name': 'Bob'}, ) 

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.


Pre-Django 1.7:

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

try:     obj = Model.objects.get(field=value)     obj.field = new_value     obj.save() except Model.DoesNotExist:     obj = Model.objects.create(field=new_value) # do something else with obj if need be 
like image 50
Platinum Azure Avatar answered Oct 20 '22 00:10

Platinum Azure


if you want only to update model if exist (without create it):

Model.objects.filter(id = 223).update(field1 = 2) 

mysql query:

UPDATE `model` SET `field1` = 2 WHERE `model`.`id` = 223 
like image 28
Eyal Ch Avatar answered Oct 19 '22 23:10

Eyal Ch