CoreyWarren / coldcmerch.com

Creating a Django/React/JWT/Redux E-Commerce store for my good friends in Cold Cut. Shout out to Elmar, Lou, and Brian.
1 stars 0 forks source link

Django: Implement Generalized Product Attributes for Better Inventory Management #89

Open CoreyWarren opened 1 year ago

CoreyWarren commented 1 year ago

We need to update our current models.py to handle multiple product attributes (e.g., size, color, and other future variants) in a more flexible and scalable way.

Here's a proposed implementation:

class Product(models.Model):
    name = models.CharField(max_length=255)
    # other product-related fields

class ProductAttribute(models.Model):
    name = models.CharField(max_length=255)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='attributes')

class ProductAttributeValue(models.Model):
    attribute = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE, related_name='values')
    value = models.CharField(max_length=255)
    added_cost = models.FloatField(default=0)
    available_amount = models.IntegerField(default=1)

In this design, each product has a set of attributes (e.g., size, color), and each attribute has a set of values (e.g., small, medium, large for size attribute). This structure allows us to easily add more attributes and values as needed, without having to modify our models each time.

To query for the available amount of a specific variant, we can filter the ProductAttributeValue model with the desired attribute and value:

def get_available_amount(product_id, attribute_name, attribute_value):
    product = Product.objects.get(id=product_id)
    attribute = product.attributes.get(name=attribute_name)
    value = attribute.values.get(value=attribute_value)
    return value.available_amount

We should also adapt our React/Redux frontend to handle the flexible attribute structure, allowing us to display and manage the inventory of product variants more easily.

Tasks: