[Fixed]-How to prevent race condition in Django on INSERT with limiting SUM?

1👍

Thanks to @Alasdair for pointing me in the right direction.

After filling out the fields of inst (a new Expense), do:

with transaction.atomic():
    project = models.Project.objects.select_for_update().get(
        pk=project_id)
    cost = project.total_cost()
    budget = project.budget

    if cost + inst.cost > budget:
        raise forms.ValidationError(_('Over-budget'))

    self._inst.save()

Note that I have total_cost defined as a method on Project:

class Project:
    def total_cost(self):
        return self.expense_set.all().aggregate(
            t=Sum(F('cost')))['t']

Leave a comment