Django:具有多种版本和价格的产品模型

时间:2018-09-28 08:50:32

标签: django django-models django-rest-framework django-views

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

例如:如果一件衬衫有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. 模型比我创建的模型有更好的选择吗?

0 个答案:

没有答案
相关问题