Justcurious
Justcurious

Reputation: 2064

How to create child django models dynamically

I want to create 73 different django models, those models will be very similar, so in theory I would inherit from a base model class and just change the name of the Model/table.

I am aware this is not the best database structure, however I believe this unconventional structure may improve other aspects of my application. The initial point is to test this hypothesis.

How can I have django create the models, without me having to define all 73 of them?

class BaseModel(models.Model):
    some_field = models.CharField(max_length=255)
    some_other_field = models.CharField(max_length=255)

class Model_NR_01(BaseModel):
    pass

...

class Model_NR_73(BaseModel):
    pass

Also, in the sample above, I believe the BaseModel would also be created. How could I prevent that, having at the end of the migration only the 73 models mentioned? (If possible, of course).

PS.: I did searched several similar questions, couldn't find an actual answer, only warnings of how bad design it is. I am aware.

Upvotes: 0

Views: 125

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

The three argument form of type can be used to create classes dynamically. The only thing you need to pass in the attributes dictionary is __module__ as using type this way to create a class will not automatically populate this attribute which is required by Django

class BaseModel(models.Model):
    some_field = models.CharField(max_length=255)
    some_other_field = models.CharField(max_length=255)

    class Meta:
        abstract = True


for i in range(1, 74):
    model_name = f'Model_NR_{i:02}'
    globals()[model_name] = type(model_name, (BaseModel, ), {'__module__': BaseModel.__module__})

Upvotes: 2

Related Questions