Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, how can I prevent a "Save with update_fields did not affect any rows." error?

I'm using Django and Python 3.7. I have this code

article = get_article(id)
...
article.label = label
article.save(update_fields=["label"])

Sometimes I get the following error on my "save" line ...

    raise DatabaseError("Save with update_fields did not affect any rows.")
django.db.utils.DatabaseError: Save with update_fields did not affect any rows.

Evidently, in the "..." another thread may be deleting my article. Is there another way to rewrite my "article.save(...)" statement such that if the object no longer exists I can ignore any error being thrown?

like image 410
Dave Avatar asked May 22 '19 14:05

Dave


1 Answers

A comment by gachdavit suggested using select_for_update. You could modify your get_article function to call select_for_update prior to fetching the article. By doing this, the database row holding the article will be locked as long as the current transaction does not commit or roll back. If another thread tries to delete the article at the same time, that thread will block until the lock is released. Effectively, the article won't be deleted until after you have called the save function.

Unless you have special requirements, this is the approach I'd take.

like image 149
Louis Avatar answered Sep 18 '22 12:09

Louis