0

here's my problem.I'm trying to create product variants which contain attribute values of the selected product. I'm trying to use JSONField to do that but I was wondering how I could dynamically display the fields in the form for creating new product variants.

Here is my models.py file:

class Product(models.Model) :
    name = models.CharField(max_length=120)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='products')
    allow_variants = models.BooleanField(default=True)
    product_attributes = models.ManyToManyField("attribute")

    def __str__(self) :
        return self.name

    class Meta :
        ordering = ("name",)

class Attribute(models.Model) :
    name = models.CharField(max_length=120)

    def __str__(self) :
        return self.name

    def get_all_attr_variants(self) :
        variants = AttributeVariant.objects.filter(attribute__name=self.name)
        return variants

class AttributeVariant(models.Model) :
    name = models.CharField(max_length=120)
    attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE)

    def __str__(self) :
        return self.name

    class Meta :
        ordering = ('name',)

class ProductVariant(models.Model) :
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    name = models.CharField(max_length=120)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    attributes = JSONField()

    def __str__(self) :
        return self.product.name + ": " + self.name

    class Meta :
        ordering = ("product.name", "name")

Please help me if you have any idea of how I could solve this problem!
Thanks

Fantasmo Clone27
  • 333
  • 1
  • 10
  • 19

0 Answers0