1
You can try like this in the LineItem
model form (explanation in code comments):
class SomeFormItem(forms.ModelForm):
...
def save(self, commit=False):
instance = super().save(commit=False)
total = instance.invoice.total # get total of line items (assuming used using reverse query)
if self.instance.pk and ('quantity' in self.changed_data or 'unit_price' in self.changed_data): # if we are editing already existing lineitem and total has been changed
total += (self.cleaned_data['unit_price'] - self.data['unit_price']) * (self.cleaned_data['quantity'] - self.data['quantity']) # self.cleaned_data contains new information and self.data contains old information and calculating the difference only
else:
total += self.cleaned_data['quantity'] * self.cleaned_data['unit_price']
if total > SOME_NUMBER:
raise ValidationError()
return super().save(commit=commit)
More information can be found in the documentation.
Source:stackexchange.com