[Django]-Django error <model> object has no attribute 'update'

75đź‘Ť

The reason for this error is that .get() returns an individual object and .update() only works on querysets, such as what would be returned with .filter() instead of .get().

If you are using .get(), then .update() will not work. You will need to save the information to the object manually:

archivo = archivo.objects.get(archivo_id=procesar)
archivo.archivo_registros = sh.nrows
archivo.save()

You can also use update_fields if you only wish to save this particular piece of data:

archivo = archivo.objects.get(archivo_id=procesar)
archivo.archivo_registros = sh.nrows
archivo.save(update_fields=['archivo_registros'])

This prevents triggering any signals that you may not want to invoke.

Your other option is to simply use .filter().

archivo = archivo.objects.filter(archivo_id=procesar).update(archivo_registros=sh.nrows)

Note that this will update multiple objects if they exist. If you want to be sure that doesn’t happen, you should include the primary key in the filter, or use one of the earlier approaches to make sure you are only modifying a single object.

11đź‘Ť

Encountered this behavior and used a “filter” then update works as expected. For example:

 Students.objects.select_for_update().filter(id=3).update(score = 10)

Just FYI: Unless you are handling transactions, modifying each field separately using save() might create data inconsistency in a multi-threaded environment. By the time threadA calls save() on a model, another threadB could have changed the model fields and saved. In which case threadA has to read the updated model and change.

This was on Django 1.6.2

3đź‘Ť

I have had similar case, but it worked when using construction like:

this_spot = Spot.objects.filter(pk=obj.spot.pk)
this_spot.update(friendly_rate=rating_to_be_persisted)

but not working in case, where I wanted access directly single instance, e.g from foreign key side class. Returning 'Spot' object has no attribute 'update'.

The reason is simply the way update() works described in django documentation:

The way around is approach like shown on the django site:

>>> b = Blog.objects.get(pk=1)

# Update all the headlines belonging to this Blog.
>>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')

0đź‘Ť

I didn’t went through all your code, but this line:

 infoarchivo2 = archivo.objects.filter(archivo_id = procesar)

does not return an instance or object from the database, it returns a Queryset, even when the Queryset just has one element. You would have to iterate the Queryset oy perhaps change the method filter for get.

As long as the method update, I don’t think it’s implemented.

Leave a comment