Race condition with django GET
I wrote a function in Django which looks roughly like this:
@login_required
def make_appointment(request):
existing_appointments = Appointment.objects.all()
print('existing_appointments = ', len(existing_appointments))
new_appointment = Appointment()
new_appointment.save()
# ...
And I call this from javascript using the following code:
for(i=0; i<2; i++){
const xhr = new XMLHttpRequest();
xhr.open('GET', "make_appointment/")
xhr.send();
}
I would expect that the GET command is called first, which in turn causes Django to execute the make_appointment
function. The log I would expect is:
[18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0
existing_appointments = 0
[18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0
existing_appointments = 1
But the log that I usually get is:
existing_appointments = 0
existing_appointments = 0
[18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0
[18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0
But I also already got
existing_appointments = 0
existing_appointments = 1
[18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0
[18/Dec/2024 17:42:48] "GET /make_appointment/ HTTP/1.1" 302 0
For me, this is problematic because the time of the second appointment depends on the existance of the first appointment so they should be created subsequently.
How can I fix this code?