问题的症结所在:一种产品可以具有不同价格的多种变化。
例如:如果一件衬衫有2种颜色选择(黑白)和2种尺寸选择(小和大),则将有4种产品变体,如下所示:
下面是我的模特:
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关系。我该怎么做?
模型比我创建的模型有更好的选择吗?