最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to Automatically Copy Product Attributes to Variants in Django Models? - Stack Overflow

programmeradmin1浏览0评论

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!

发布评论

评论列表(0)

  1. 暂无评论