[Answered ]-How to add model field dynamically?

2👍

Creating columns dynamically is not impossible with Django but you’ll have to do it using a metaclass and/or inheritance.

For your problem the easiest solution would probably be something like this:

if django_is_not_non_rel:
    class ModelABase(models.Model):
        MyModel.all_modelb = models.ManyToManyField(ModelB, through="ModelAB")

        class Meta:
            abstract = True

else:        
    class ModelABase(models.Model):
        class Meta:
            abstract = True

class ModelA(ModelABase):
   pass # whatever

Or even simpler (if you don’t need as much customization):

class ModelAORMBase(models.Model):
    MyModel.all_modelb = models.ManyToManyField(ModelB, through="ModelAB")

    class Meta:
        abstract = True

if django_is_not_non_rel:
    ModelABase = ModelAORMBase
else:
    ModelABase = models.Model

class ModelA(ModelABase):
   pass # whatever
👤Wolph

Leave a comment