Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
            )
        ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading