我正在尝试为产品的重量添加不同的价格,并且需要在用户选择重量的顺序中节省成本。
class ProductPrice(models.Model):
QUANITY = (
(1, '1'),
(3, '3'),
(5, '5'),
...
)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices')
price = models.IntegerField(default=0)
quanity = models.CharField(max_length=3, default=1, choices=QUANITY)
在Order模型中,我重写了save方法:
class ProductInOrder(models.Model):
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
nmb = models.IntegerField(default=1)
price_per_item = models.IntegerField(default=0)
total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
def save(self, *args, **kwargs):
if self.nmb > 3:
quanity = 1
self.price_per_item = self.product.prices.get(quanity=quanity).price
elif self.nmb >= 5:
quanity = 5
self.price_per_item = self.product.prices.get(quanity=quanity).price
elif self.nmb >= 10:
quanity = 10
self.price_per_item = self.product.prices.get(quanity=quanity).price
elif self.nmb >= 20:
quanity = 20
...
return super(ProductInOrder, self).save(*args, **kwargs)
但这不是我需要的。它很可能会触发一个DoesNotExist。 如何实现呢?
答案 0 :(得分:0)
所以看起来你想要一张桌子来检索产品和重量的每磅价格。
class PricePerPound(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices')
weight = models.IntegerField(max_length=8, default=1)
priceperlb = models.DecimalField(default=0.00)
如果您将重量存储为相应价格的最大重量,则可以检索select priceperlb from PricePerPound where product = product.id and weight >= orderweight order by weight limit 1
修改强>
填充此表,最终会得到一个像这样的表
product | weight | price per wt
______________________________________
sugar | 5 | 2.00
sugar | 10 | 1.50
sugar | 20 | 1.25
sugar | 999999 | 1.15
salt | 5 | 1.00
salt | 15 | .80
salt | 50 | .65
salt | 999999 | .55
使这项工作的诀窍在于该查询,该查询获取与所讨论的产品相对应的价格以及下一个高于订购金额的重量。因此,如果有人订购5公斤或更少的糖,他们会得到5公斤或更少的糖价。如果他们订购8公斤,他们就会得到5到10公斤的价格