[英]Django get value from foreign key when the object was instantiated
我正在寫一個簡單的在線訂購應用程序。 物品價格更新時遇到問題。 已完成的訂單也會改變價格。 我希望產品的訂單在訂單完成時有價格,而不是從最新價格的產品型號獲得。
換句話說,當您在亞馬遜上購買物品時,您的訂單將在您購買物品時具有價格,因此價格會發生變化,它仍將保留為您訂單中的舊價格(意味着數量*價格)將正確加起來)。
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)
我不認為你的模型設置得很對。 嘗試這個:
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
上放一個save方法來計算價格並將其存儲在表中。 您還可以在此步驟中處理稅,折扣,運費等。
這是它通常在電子商務中完成的方式。
- 在if語句之外移回self.product_price * self.quantity
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.