On Tue, Apr 22, 2008 at 4:47 PM, Don Spaulding <[EMAIL PROTECTED]> wrote:
>
>  I think I must have fallen through the cracks of "nobody will ever
>  want to do *this*" when building this app.  Given the following two
>  models (simplified for clarity):
>
>  class Order(models.Model):
>     total = models.DecimalField(...)
>
>     def save(self):
>         tmp_total = Decimal()
>         for item in self.items.all():
>             tmp_total += item.price
>         self.total = tmp_total
>         super(Order, self).save()
>
>  class Item(models.Model):
>     order = models.ForeignKey(Order, related_name='items')
>     price = models.DecimalField(...)
>
>     def save(self):
>         super(Item, self).save()
>         self.order.save()
>
>  I try to do something like this:
>
>  order = Order()
>  order.save()
>  order.items.create(price=Decimal("5.00"))
>  order.total         #gives me 0
>  order.save()
>  order.total         #gives me the correct order.total
>
>  My guess is that even though I've saved the item before calling
>  order.save(), the order objects still doesn't know that the new item
>  is related to it.  Anybody know if this is expected behavior?
>
well you have a clean error of separation of the MVC layers, I believe
that operation should be done on the controller instead of when saving
the object.
also you may want to look at the sum() function in python, I'm sure
you can do better than that for, that cycle is so unpythonic.

the reason for the value not being updated is that your model objects
are proxy object, the real data is in the db. and it's only updated,
when needed. when you do Order() order.total = 0 (as that's the
default) after you call safe, the changes are reflected in the db, and
the order.total value is updated with it's new value. This is the
correct behavior to emulate the transactional nature of the db.

>  Thanks,
>  Don
>  >
>

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to