【问题标题】:Django get value from foreign key when the object was instantiated实例化对象时,Django从外键获取值
【发布时间】:2013-12-28 12:02:15
【问题描述】:

我正在编写一个简单的在线订购应用程序。商品价格更新时遇到问题。已完成的订单也会更改价格。我想让产品的订单有订单完成时的价格,而不是从最新价格的产品模型中获取。

换句话说,当您在亚马逊上购买某件商品时,您的订单将具有您购买该商品时的价格,因此如果价格发生变化,它仍将保持您订单中的旧价格(这意味着数量 * 价格将正确相加)。

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)

【问题讨论】:

  • 欢迎来到stackoverflow!您可能想让您的问题更清楚一点 - 代码 sn-ps 等很棒,但不确定您要的是什么。
  • 我希望订单中的商品具有创建订单时的商品价格,而不是商品的最新价格。
  • 我想我已经明白了。我必须简单地在 ProductQuantity 模型中添加一个价格字段,并将其设置为实例化的价格产品价格。因为我使用 Product 作为外键,所以我一直在寻找替代方案。请让我知道是否有其他解决方案。当对象被隐式实例化时,有没有办法将其设置为产品的价格,也许是通过 def create() ?

标签: python django foreign-keys instance


【解决方案1】:

我认为您的模型设置不正确。试试这个:

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 上添加一个保存方法来计算价格并将其存储在表格中。您还可以在此步骤中处理税金、折扣、运费等。

这是电子商务中通常采用的方式。

-- 将 self.product_price * self.quantity 移回 if 语句之外

【讨论】:

  • 感谢您提出的解决方案!我正在研究编辑 __init__() 类似stackoverflow.com/questions/7884376/… 的解决方案是否也可以工作?
  • 我不确定你是否可以使用__init__(),因为我不确定self.product_price 的状态是什么。我们知道在调用save() 时这将是一个准确的比较。将对象写入数据库时​​会触发保存。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 2018-12-01
  • 1970-01-01
相关资源
最近更新 更多