On May 13, 11:28 am, Alfonso <allanhender...@gmail.com> wrote:
> Discovered a weird bug in my custom save method for a model.  Setup is
> a simple invoice model linked to multiple invoice order models (fk to
> invoice) and the invoice model holds data like total number of units
> of ordered... i.e.
>
> Invoice order 1:
> 2 x X DVD @$9.99
> Invoice order 2:
> 5 x Y DVD @$9.99
>
> Invoice:
> Total units: 7
>
> So to get that invoice total I have a custom save method:
>
> def save(self):
>   # Grab total invoice units
>   units = 0
>   for item in self.customer_invoice_orders.all():
>     units += item.quantity
>   self.invoice_units = units
>   super(CustomerInvoice, self).save()
>
> This is all set up in admin with invoice order inlines so the admin
> user can edit and add to related invoice orders.
>
> I thought it all works fine but if I adjust the quantity figure in an
> inline invoice order and hit save the new total in the parent invoice
> doesn't get updated, only gets updated if I hit save and continue
> first, then save again.
>
> I'm sure it's something very elementary I'm overlooking
>
> Thanks

I expect this is happening because inlines are saved *after* the
parent model. So, think what happens: you click save, and Django first
goes to save the invoice. It goes to the database to get all the
existing InvoiceOrders, but only finds the old values because the new
ones haven't been saved yet. Only then does it go and save the
inlines. But the second time you click save, the new values in the
inlines have already been saved, so it picks them up, and properly
updates your parent model.

I can't think of a very good way of solving this. One possibility
might be to put the update code in the form, rather than the model.
--
DR.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to