Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Creating model fields from list with for loop

Tags:

python

django

I have a long list of 100 labels I need my model to have as fields and to also call in succession to access them in other parts of code. I am going to need to modify them in the future so I would like to be able to do it in one place. Is there a simple way to do this. For example:

labels = ['height', 'weight', 'age']

In models.py

class MyModel(models.Model):
    for label in labels:
        label = models.CharField(max_length=255)

Would the above be equal to :

class MyModel(models.Model):
    height = models.CharField(max_length=255)
    weight = models.CharField(max_length=255)
    age = models.CharField(max_length=255)
like image 234
Red-Tune-84 Avatar asked Jul 13 '14 18:07

Red-Tune-84


2 Answers

Django models have an add_to_class method which adds a field (or any attribute, really) to a class. The syntax is MyModel.add_to_class(name, value). The resulting code would be:

class MyModel(models.Model):
    pass

for label in labels:
    MyModel.add_to_class(label, models.CharField(max_length=255))

Internally, this will call the contribute_to_class method on the value passed, if that method exists. Static attributes are added to the class as-is, but fields have this method and all subsequent processing will ensue.

like image 154
knbk Avatar answered Oct 19 '22 19:10

knbk


Using locals() should work here:

class MyModel(models.Model):
    for label in labels:
        locals()[label] = models.CharField(max_length=255)

    del locals()['label']
like image 32
Eric Avatar answered Oct 19 '22 19:10

Eric