django - Django:具有多种变体和定价的产品模型
问题描述
问题的症结:一种产品可以有多种价格不同的变体。
例如:如果一件衬衫有 2 种颜色选择(黑色和白色)和 2 种尺寸选择(小号和大号),则将有 4 种产品变体,如下所示:
- 衬衫 - 颜色:白色,尺码:大,价格:12 美元,
- 衬衫 - 颜色:白色,尺寸:小,价格:10 美元,
- 衬衫 - 颜色:黑色,尺码:大,价格:14 美元,
- 衬衫 - 颜色:黑色,尺码:小号,价格:10 美元
下面是我的模型:
class Product(models.Model):
"""
This model holds all common fields of a product
"""
name = models.CharField(max_length=155)
class ProductAttribute(models.Model):
"""
This model holds the attr_type (ex: color) and attribute_name (ex: red)
"""
product = models.ForeignKey(Product, on_delete=models.CASCADE)
attr_type = models.ForeignKey(
VariantType, on_delete=models.PROTECT, blank=True, null=True)
attr_name = models.CharField(max_length=155, blank=True)
class ProductVariant(models.Model):
"""
This model holds the values for price and combination of attributes
"""
product = models.ForeignKey(Product, on_delete=models.CASCADE)
variant = models.ManyToManyField(ProductAttribute)
sku = models.CharField(max_length=155, blank=True)
price = models.DecimalField(max_digits=25, decimal_places=2)
我想知道两件事:
我必须先保存产品属性(ProductAttribute 模型),然后在 ProductVariant 模型中创建特定的 m2m 关系。我该怎么做呢?
有没有比我创建的模型更好的选择?
解决方案
推荐阅读
- core-data - 如何使用 NavigationLink 创建 CoreData 对象并将其传递给子 NavigationView
- verilog - 在接口内实例化 nmos (UVM)
- filter - 您可以在 Shopify 中覆盖 Product.tags 吗?
- python-3.x - 尝试自动化 Instagram 登录
- java - 数组。如何索引?
- deployment - 我是詹金斯的新手。我能够访问 Tomcat Web 应用程序管理器,但是当我尝试部署它时出现以下错误。如何解决这个问题
- random - 如何创建随机纹理?
- mysql - 编码未正确呈现
- c# - 在 Blazor 中移动子元素时防止 onmouseout 触发
- cuda - 尝试使用超过 48 KB 的(静态)共享内存时出错