Search code examples
djangoe-commerceproduct-variations

Django Products model for e-commerce site


I am trying to build a sample e-commerce site with Django and I am trying to figure out as to how can I model the relationship between a product having multiple sizes and each of those sizes having their individual stocks this my products/products varied models:

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
  

Solution

  • Given I understand the problem correctly, you should make a variant for combinations of product, size and color, so with ForeignKeys to the three other models. Furthermore you can make a UniqueConstraint to prevent entering the same ProductVariant for the color/size/product 3-tuple. The ProductVariant model then can also have an IntegerField with the number of items in stock:

    class ProductVaraiant(models.Model):
        product = models.ForeignKey(Product,on_delete=models.CASCADE)
        color = models.ForeignKey(Color,on_delete=models.CASCADE)
        size = models.ForeignKey(Size, on_delete=models.CASCADE)
        amount_in_stock = models.IntegerField()
    
        class Meta:
            constraints = [
                models.UniqueConstraint(
                    fields=['product', 'color', 'size'],
                    name='unique_prod_color_size_combo'
                )
            ]