Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: select_for_update() on Foreign Key Relation

I've used select_for_update() a lot. However, in all the cases I've used it, it has been through a manager like so:

with transaction.atomic():
    transaction = Transaction.objects.select_for_update().get(id="12345-6789-10")
    transaction.status = StatusEnum.APPROVED
    transaction.save()

However, I sometimes get the transaction via a reference from another object.

For example:

transaction = another_object.transaction
transaction.status=StatusEnum.APPROVED
transaction.save()

^^ This will not lock the row. Instead, I would have to do this:

transaction = Transaction.objects.select_for_update().get(id=another_object.transaction.id)

My question: if another object has a foreign key relation to a Transaction, is there a way to lock the Transaction object without writing a get query? I understand performance-wise both options are about the same. Just looking for something a bit cleaner. Thanks!

like image 510
Dougyfresh Avatar asked Jul 05 '18 18:07

Dougyfresh


1 Answers

I have found the answer since upgrading to Django 2.0. See this answer on GitHub:

django select_for_update and select_related on same query?

You can use select_related with select_for_update that will lock the respective row in each table.

like image 172
Dougyfresh Avatar answered Oct 21 '22 10:10

Dougyfresh