I have successfully changed a particular field net
in my object based on the quantity qty
field with the following code.
class OrderDetailsProductEdit(UpdateView):
model = OrdersPlaced
fields = ['qty']
template_name = 'backend/order-details-product-edit.html'
success_url = '../../../'
def form_valid(self, form):
form.instance.net = form.instance.qty * form.instance.price
# order = Order.objects.get(pk=self.kwargs['order_id'])
# subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']
# order.subtotal = subtotal
# order.save()
return super(OrderDetailsProductEdit, self).form_valid(form)
However, I am also trying to change the data in ANOTHER model. To be precise, I want the summation of all net
values of a query and update the subtotal
field in another table.
Please notice the commented out lines under def form_valid
. I have no confusion that these lines work, but I need them to execute AFTER the current model is saved, as those are dependent on the value of the current model.
I don't find any errors other than that the subtotal
field in ANOTHER model is calculated BEFORE the net
field in the current model is saved. Thus, the total is a wrong answer.
What am I doing wrong?
Simply move the instruction after calling super
def form_valid(self, form):
form.instance.net = form.instance.qty * form.instance.price
redirect_url = super(OrderDetailsProductEdit, self).form_valid(form)
order = Order.objects.get(pk=self.kwargs['order_id'])
subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']
order.subtotal = subtotal
order.save()
return redirect_url
or just do what calling super
does (save model and redirect to success_url
) by yourself
def form_valid(self, form):
form.instance.net = form.instance.qty * form.instance.price
self.object = form.save()
order = Order.objects.get(pk=self.kwargs['order_id'])
subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']
order.subtotal = subtotal
order.save()
return HttpResponseRedirect(self.get_success_url())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With