I have a form that corresponds to Model A available in models.py which has an "amount" field. I also have a Model B which also has a "total_amount" field. When creating a new Model A through it's corresponding form, after form submition I want to save Model A and modify the total_amount field of Model B so it is : ModelB.total_amount += ModelA.amount. I represented this logic through this lines of code :
def form_valid(self, form):
self.object = form.save(commit=False)
amount_to_add = form.cleaned_data['amount']
model_b = utils.get_model_b_by_currency(form.cleaned_data['currency'])
model_b[0].total_amount = model_b[0].total_amount + amount_to_add
model_b[0].save()
self.object.save()
return super(ModelFormMixin, self).form_valid(form)
The code is executed correctly, Model A is created, but Models B "total_amount" field is not updated with the new value.
Any idea would be very helpful.
Your
get_model_b_by_currency
is returning a queryset rather than a single instance. Every time you slice a queryset, you get a new instance. Instead, either return an instance fromget_model_b_by_currency
- for instance by usingget()
instead offilter()
- or slice it once, allocate it to a variable, and modify and save that variable.