11. Adding color class

The first feature implemented in the product detail page will be a color filter that displays the available color options and the corresponding stock count for each. This feature will be presented as a set of color swatches.

To efficiently manage and utilize different colors for our products, we'll create a Color class within the models.py file. Each color instance will contain a name and its corresponding hexadecimal code.

models.py
class Color(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    code = models.CharField(max_length=200, null=True, blank=True) #? color code is a hex code

    def __str__(self) :
        return str(self.name)

Given that the Color class has been defined, we need to modify the ItemStock class to establish a relationship with this new class. We'll update the color parameter in ItemStock to use a ForeignKey that references the Color class. This approach allows each item in stock to be associated with a specific color object, ensuring data integrity and enabling effective querying based on color attributes.

models.py
class ItemStock(models.Model):
    product = models.ForeignKey(Product, blank=True, null=True, on_delete=models.SET_NULL) #? one itemstock is associated to a single product however one product can have many itemstocks
    color = models.ForeignKey(Color, blank=True, null=True, on_delete=models.SET_NULL)
    size = models.CharField(max_length=200, null=True, blank=True)
    quantity = models.IntegerField(default=0)

Lastly, we will add the Color class to our admin page via the admin.py file:

admin.py
admin.site.register([Categoric, Client, Type, Product, ItemStock, Order, OrderedItem, Adres, Banner, Color])

Making the migrations via the command prompt, remember to be inside the main ecommerce folder (cd ecommerce) :

cmd prompt
python manage.py makemigrations
cmd prompt
python manage.py migrate

Inside the admin page we can now add different colors:

Creating new color
Added various colors

Last updated