2013-12-10 54 views
0

我在寫一個簡單的在線訂購應用程序。物品價格更新時遇到問題。已完成的訂單也會改變價格。我希望在訂單完成時與產品的訂單具有價格,而不是從最新價格的產品型號中獲得。Django在實例化對象時從外鍵獲取值

換句話說,當您在亞馬遜物品上進行購買時,您的訂單將在您購買該物品時收取價格,因此價格會發生變化,它仍然會保留爲訂單中的舊價格(含義數量*價格將正確加和)。

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

歡迎來到stackoverflow!你可能想讓你的問題更清楚一點 - 代碼片段很棒,但不知道你在問什麼。 –

+0

我希望訂單中的商品具有創建訂單時的商品價格,而不是該商品具有的最新價格。 – cleung2010

+0

我想我已經想通了。我必須在ProductQuantity模型中簡單地添加一個價格字段,並在實例化時將其設置爲價格產品價格。自從我將產品用作外鍵以來,我一直在尋找替代產品。請讓我知道是否有其他解決方案。 當對象被隱式地實例化時,有沒有辦法將它設置爲產品的價格,也許是通過def create()? – cleung2010

回答

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

+0

感謝您提出的解決方案!我正在尋找編輯__init __()將類似於http://stackoverflow.com/questions/7884376/can-a-django-model-fields-default-value-be-defined-by-a-function-依賴於一項工作呢? – cleung2010

+0

我不確定你可以使用'__init __()',因爲我不確定'self.product_price'的狀態是什麼。我們知道在save()被調用的時候它會是一個精確的比較。將對象寫入數據庫時​​,保存將會觸發。 –