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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With