我正在写一个简单的在线订购应用程序。物品价格更新时遇到问题。已完成的订单也会改变价格。我希望产品的订单在订单完成时有价格,而不是从最新价格的产品型号获得。
换句话说,当您在亚马逊上购买商品时,您的订单将在您购买商品时具有价格,因此价格会发生变化,它仍将保留为订单中的旧价格(意味着数量*价格将正确加起来。)
class ProductQuantity(models.Model):
product = models.ForeignKey('Product')
order = models.ForeignKey('Order')
quantity = models.PositiveIntegerField(default=1)
ready = models.BooleanField(default=False)
def __unicode__(self):
return '[' + str(self.order.pk) + '] ' + \
self.product.name + ' (' + self.product.unit + '): ' + str(self.quantity)
class Meta:
verbose_name_plural = "Product quantities"
class Order(models.Model):
customer = models.CharField(max_length=100, default="")
phone = models.CharField(max_length=20, default="")
email = models.CharField(max_length=50, default="")
collection = models.ManyToManyField(Product, through=ProductQuantity)
def __unicode__(self):
return str(self.pk)
答案 0 :(得分:2)
我认为你的模型设置得不对。试试这个:
class Order(models.Model):
customer = models.CharField(max_length=100, default="")
phone = models.CharField(max_length=20, default="")
email = models.CharField(max_length=50, default="")
sub_total = .....
tax = .....
shipping = ....
total = .....
def __unicode__(self):
return str(self.pk)
class OrderProduct(models.Model):
product = models.ForeignKey(Product)
order = models.ForeignKey(Order)
product_price = models.DecimalField()
quantity = models.IntegerField()
product_line_price = models.DecimalField()
def save(self, *args, **kwargs):
# If this OrderProduct doesn't have a price, it is new.
# So get the current Product.price and store it.
if not self.product_price:
self.product_price = self.product.price
# optional
self.product_line_price = self.product_price * self.quantity
super(OrderProduct, self).save(*args, **kwargs)
现在我还要在Order
上设置一个保存方法来计算价格并将其存储在表格中。您还可以在此步骤中处理税,折扣,运费等。
这是通常在电子商务中完成的方式。
- 在if语句
之外移回self.product_price * self.quantity