电子商务网站的 Django 产品模型

Django Products model for e-commerce site

我正在尝试使用 Django 构建一个示例电子商务网站,并且我正在尝试弄清楚如何为具有多种尺寸的产品与具有各自库存的每种尺寸之间的关系建模 这是我的 products/products 多种型号:

from django.db import models
from colorfield.fields import ColorField
# Create your models here.



class Color(models.Model):
   
    Color = models.CharField(max_length=120,null=True,blank=True)
    value =  ColorField(default='#FF0000')

    def __str__(self):
        return self.Color


class Size(models.Model):
   
    Size = models.CharField(max_length=120,null=True,blank=True)

    def __str__(self):
        return self.Size
  

class Product(models.Model):
   
    title = models.CharField(max_length=120,null=True,blank=True)
  


    def __str__(self):
        return self.title


class ProductVaraiant(models.Model):
    product = models.ForeignKey(Product,on_delete=models.CASCADE,null=True,blank=True)
    slug  = models.CharField(max_length=120,null=True,blank=True)
    Color = models.ForeignKey(Color,on_delete=models.CASCADE,null=True,blank=True,)
    Size  = models.ManyToManyField(Size)


    def __str__(self):
        return self.slug
  

鉴于我对问题的理解正确,你应该为 productsizecolor 的组合做一个变体,所以 ForeignKeys 到其他三个楷模。此外,您可以创建一个 UniqueConstraint 来防止为 color/size/product 三元组输入相同的 ProductVariantProductVariant 模型也可以有一个 IntegerField 以及库存商品的数量:

class ProductVaraiant(models.Model):
    product = models.<strong>ForeignKey(</strong>Product,on_delete=models.CASCADE<strong>)</strong>
    color = models.<strong>ForeignKey(</strong>Color,on_delete=models.CASCADE<strong>)</strong>
    size = models.<strong>ForeignKey(</strong>Size, on_delete=models.CASCADE<strong>)</strong>
    amount_in_stock = models.IntegerField()

    class Meta:
        constraints = [
            models.<strong>UniqueConstraint(</strong>
                fields=['product', 'color', 'size'],
                name='unique_prod_color_size_combo'
            <strong>)</strong>
        ]