Create django model with as many fields as an integer in other field

466 Views Asked by At

I have the following model in django

class params(models.Model):
    name = models.CharField(max_length=30, default = 'no_name')
    cs_n = models.IntegerField(default=16)
    alt_n = models.IntegerField(default=2)
    opt_out = models.BooleanField(default=1)
    at_n = models.IntegerField(default=4)

I want to create a new model with as many fields as at_n. For example, if the user enter "4" in at_n, I want this to create automatically:

class params(models.Model):
    at_1 = models.IntegerField(default=2)
    at_2 = models.IntegerField(default=2)
    at_3 = models.IntegerField(default=2)
    at_4 = models.IntegerField(default=2)

Thanks

1

There are 1 best solutions below

0
On

This probably isn't a good data model to follow as Django models are intended to closely mirror database tables. For example, you wouldn't want to dynamically update the DDL of a table in a database because doing so places you at risk of messing up data that already exists in said table.

Instead, I think it would be a better approach for you to re-evaluate your data model.

For example, if there was a main object you were trying to tie these attributes to, then make a model for that main object and then make a separate model for main object attributes/values.

From there, you could use view logic to actually validate that the appropriate number of attributes assigned to a particular main object.

I'm thinking something kind of like this:

class MainModel(models.Model):
    ....
    {Your main model attributes}
    at_n = models.IntegerField(default=4)
    ....


class MainModelAttributes(model.Model):
    main_model = models.ForeignKey(MainModel)
    attr_value = models.IntegerField()

Then in your views.py file, you could use logic to make sure that the number of attributes on the MainModelAttributes model match the number stored in MainModel.at_n.