Request Handling at backend (Django)
I have two api endpoints
1- stockpurchases/ || stockpurchases/{id}/
2- stockpurchases/{id}/stocks/ || stockpurchases/{id}/stocks/{id}/
So if some one want to purchase he should create a stockpurchase first and than add a stock to it and when someone POST stock I plus quantity and amount of stockpurchase.
The problem is if some one call POST request consecutively for a loop the amount operation will goes incorrect.
I want handle multiple request at the backend. Supose if the server gets consecutive request to perform operation how can i make others request wait till completion of first procedsed. After that second request is processed and so on.
StockPurchase Model
class StockPurchase(models.Model):
qty = models.IntegerField(default=0)
amount = models.IntegerField(default=0)
Stock Model
class Stock(models.Model):
stockpurchase = models.ForeignKey("StockPurchase", on_delete=models.CASCADE, related_name='stocks')
product = models.ForeignKey("Product", on_delete=models.CASCADE, related_name='stocks')
project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name='stocks')
rate = models.IntegerField()
def save(self, *args, **kwargs):
if not self.pk:
self.stockpurchase.amount += self.rate
self.stockpurchase.qty += 1
self.stockpurchase.save()
super().save()
So if I Call like this with await no issue
async function create() {
for (let i = 0; i < 10; i++) {
let response = await fetch(
"http://localhost:8000/api/stockpurchases/2/stocks/",
{
method: "POST",
body: bodyContent,
headers: headersList,
}
);
}
}
but if call it without await async function the amount of stockpurchase will be wrong like this
for (let i = 0; i < 10; i++) {
let response = fetch("http://localhost:8000/api/stockpurchases/2/stocks/", {
method: "POST",
body: bodyContent,
headers: headersList,
});
}