I have a problem with usage of select_for_update() with select_related() and foreign key can be null. The way with select_for_update(of=(self,)) is not a solution, because I need no lock related rows too. How can I solve this issue in Django?
Have you tried
Model.objects.select_for_update(of=("self", "related_model")) where
related_model is what you’re using in
This will cause an error, because we try to lock nonexisting row in case related_object is None. We cant use select_for_update with select_related, if related objects can be null. I dont know how to save locks of related objects if they are not null and on the other hand avoid an issue with error.
I’ve seen other folks come across this recently. It’s not a Django issue, but a database issue. At a database level, doing a
SELECT ... FOR UPDATE with a
LEFT JOIN doesn’t work out of the box. I saw a few cases where folks use a view or a nested query to get this to work, but maybe if you search for
<your database> select for update with left join, you’ll find more info.