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!
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.
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