How to implement different model fields for different categories?

Viewed 48

I have 2 models like this:

class Category(MPTTModel):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)


class Product(models.Model):
    name = models.CharField(max_length=70)
    category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
    slug = models.SlugField(unique=True)
    description = models.TextField(max_length=300)

and in every Category i need my Product to have multiple additional fields for example processors(Category#1) and SSD drives(Category#2)

Category#1-Product#1(-/-, total_cores, total_threads, ..), Product#2(-/-, total_cores, total_threads, ..), ...

Category#2-Product#3(-/-, storage_capacity, connector, ..), Product#4(-/-, storage_capacity, connector, ..), ...

Is there any way to add fields to Product depending on the Category it belongs to or i need to create models for each Category?

1 Answers

One possible solution to this could be to use JsonField if you're using Postgresql as a database

from django.contrib.postgres.fields import JSONField

    class Product(models.Model):
        name = models.CharField(max_length=70)
        category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
        slug = models.SlugField(unique=True)
        description = models.TextField(max_length=300)
        product_features = JSONField()
Related