Issue
The answer to my question may probably be obvious, but I'd like to find out for myself.
I love Django ORM and use it in almost all my projects. I'm currently developing a telegram bot using Pyrogram (available in asynchronous mode with async await + asyncio.run), and I want to use Django ORM in it.
Let me give a simplified example of my task. There is a button that is bound to an object in the database, each click of which should decrease a field in one object and increase another field in another, conditionally:
async def on_button_click():
obj1 = Object1.objects.get(id=X)
if obj1.filed1 > 0:
obj2 = Object2.objects.get(id=X2)
obj1.field1 -= N
obj2.field2 += N
obj1.save()
obj2.save()
However, I am worried that this may cause a race condition and the result of executing this code with several simultaneous button clicks may differ from what is expected (both in the if condition and when further saving objects).
Please tell me what are the best practices for handling such tasks. Is select_for_update
method would cover my needs?
If Django ORM is not a good solution for this, what ORMs or database libraries should I look at? If Django ORM is suitable, what exactly is the best way to handle such tasks? Thank you so much in advance for your help!
Solution
You can certainly use select_for_update()
, but seeing you're working with multiple models, I think wrapping the if
block (or better still, the entire view) in an transaction.atomic decorator would be less verbose.
You might also need to at F expressions. They allow you, in this case, update the values at database level.
Answered By - McPherson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.