Django - Creating model fields from list with for loop

django, python

Solution

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.

Problem

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) ```

Original source

Related problems