Koen Bok wrote: > I'd like to build object relations (Model classes) without saving them > to the database to predict a price for a specific order. Let's say I > have this: > > class Order(Model): > id = models.AutoField(primary_key=True) > number = models.IntegerField() > > def total(self): > return sum([p.price for p in self.product_set]) > > class Product(Model): > id = models.AutoField(primary_key=True) > order = models.ForeignKey(Order) > price = models.DecimalField() > > order = Order(number=1) > > # Now the nex line throws an error if we did not save the order here > order.product_set.create(Product(price=20.0)) > > assert order.total() == 20.0
That would be very hard i think(relations work with primary keys and typically primary keys are only exist after save. An alternative solution is to make a method that takes a set of products and produces total for them. I'd proly put sum_products in an OrderManager or maybe ProductManger but not bothering with that here. class Order(Model): id = models.AutoField(primary_key=True) number = models.IntegerField() def total(self): return sum_products(self.product_set) def sum_products(self, products): # maybe some other logic here such as customer discount, tax calc, etc. return sum([p.price for p in products]) def test_sum_products(self): order = Order(number=1) product_list = [Product(price=20.0), ] self.assertEqual( 20.0, order.sum_products(product_list) ) -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___________________________________________________________________________ Get off the sidelines and huddle up with the Statesman all season long for complete high school, college and pro coverage in print and online! --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---