如何在Django中捕获对象的状态?
我在Django开发了一个web应用程序来记录零售店的销售额。 我的项目中有以下两个模型:如何在Django中捕获对象的状态?,django,django-models,Django,Django Models,我在Django开发了一个web应用程序来记录零售店的销售额。 我的项目中有以下两个模型: class Product(models.Model): code = models.CharField(max_length=256) name = models.CharField(max_length=256) description = models.CharField(max_length=2048) cost_price = models.DecimalFiel
class Product(models.Model):
code = models.CharField(max_length=256)
name = models.CharField(max_length=256)
description = models.CharField(max_length=2048)
cost_price = models.DecimalField(max_digits=8, decimal_places=2)
retail_price = models.DecimalField(max_digits=8, decimal_places=2)
class Sale(models.Model):
date = models.DateTimeField(default=timezone.now)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
我遇到的问题是,当我编辑产品的价格时,它也会影响该产品过去的销售。这是因为产品是销售模式的外键。
确保所有销售不受产品编辑影响的最佳方法是什么
我考虑在销售模型中添加一个价格字段,以确保价格保持不变,如下所示:
class Sale(models.Model):
date = models.DateTimeField(default=timezone.now)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=8, decimal_places=2)
然而,我不确定这是否是最好的解决方案,它似乎在某种程度上是硬编码的。
如果有任何建议,我将不胜感激。我认为您需要创建另一个模型来保存销售产品,例如,您可以创建包含销售id、产品id、数量、sub_total等的SaleDetail模型,然后您可以从销售模型中删除product foreignkey。我认为您需要创建另一个模型来保存销售产品,例如,您可以创建包含sale_id、product_id、quantity、sub_total等的SaleDetail模型,然后可以从sale模型中删除product foreignkey。