Django handle transaction on filter query

I have a Model that has a "score" attribute and a route that returns the object with the biggest score from the database (MySQL).

I want to use multiple instances of the same application (two microservices) and I am afraid that I will face race conditions, both machines returning the same client. How could I make sure that this is not happening? After returning a client, it will be marked as PROCESSED.

def getClient(request):
    client = Client.objects.order_by('-score').filter(state="UNPROCESSED").first()
    client.state = "PROCESSED"
    client.save()
    return HttpResponse(f"<h1>{client.name}</h1>")

In the official document, the transaction processing is well described.

https://docs.djangoproject.com/en/4.0/topics/db/transactions/

Back to Top