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)
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.
Using locals()
should work here:
class MyModel(models.Model):
for label in labels:
locals()[label] = models.CharField(max_length=255)
del locals()['label']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With