首页 > 解决方案 > Django:具有多种变体和定价的产品模型

问题描述

问题的症结:一种产品可以有多种价格不同的变体。

例如:如果一件衬衫有 2 种颜色选择(黑色和白色)和 2 种尺寸选择(小号和大号),则将有 4 种产品变体,如下所示:

  1. 衬衫 - 颜色:白色,尺码:大,价格:12 美元,
  2. 衬衫 - 颜色:白色,尺寸:小,价格:10 美元,
  3. 衬衫 - 颜色:黑色,尺码:大,价格:14 美元,
  4. 衬衫 - 颜色:黑色,尺码:小号,价格: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)

我想知道两件事:

  1. 我必须先保存产品属性(ProductAttribute 模型),然后在 ProductVariant 模型中创建特定的 m2m 关系。我该怎么做呢?

  2. 有没有比我创建的模型更好的选择?

标签: djangodjango-modelsdjango-rest-frameworkdjango-views

解决方案


推荐阅读