'Django add a field to a model based on another model

I have a model for a product:

class Product(models.Model):
    name = models.CharField(verbose_name=_("Name"), max_length=120)
    slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True)

I want to have a separate model ProductFields:

class ProductFields(models.Model):
   field_name = models.CharField()
   field_type = models.CharField()
   field_verbose_name = models.CharField()
   field_max_length = models.IntegerField()
   filed_null = models.CharField()
   field_blank = models.BooleanField()
   field_default = models.CharField()
...

So the idea is whenever I add new ProductField I want Product model to migrate that added field to its database.

For Example:

ProductFields.objects.create(field_name='description', field_type='CharField', field_verbose_name='Description', field_max_length=255, filed_null=True, filed_blank=True)

This should transform Product modal to:

class Product(models.Model):
    name = models.CharField(verbose_name=_("Name"), max_length=120)
    slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True)
    description = models.CharField(verbose_name="Description", max_length= 255, null=True, blank=True)

Please let me know if you have any idea how this can be done?



Solution 1:[1]

If you're looking for a way to create a dynamic model you can look into these suggestions.

  1. HStoreField using django-hstore : https://django-hstore.readthedocs.io/en/latest/
  2. JSONField: JSONField is similar to HStoreField, and may perform better with large dictionaries. It also supports types other than strings, such as integers, booleans and nested dictionaries.https://django-pgfields.readthedocs.io/en/latest/fields.html#json-field

Or you can use a NoSQL database (Django MangoDB or another adaptation)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Blurryface