I am building an e-commerce website in Django where:
- A
Product
can have multiple variants. - Each product has attributes (e.g., color, storage, display size).
- I want each variant to automatically inherit all attributes from the main product when it is created.
Models (models.py
)
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
class ProductVariant(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants")
name = models.CharField(max_length=255) # Example: "Iphone 16 Black 128GB"
class ProductAttribute(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="attributes")
attribute_name = models.CharField(max_length=255)
attribute_value = models.TextField()
What I Want to Achieve:
- When a ProductVariant is created, it should automatically copy all attributes from its main product.
- What is the best way to do this in Django?
I want a clean and efficient solution that works well even if I have many variants.
Any guidance would be appreciated. Thank you in advance!