For a project I needed to create a Django model from a list of fields that were defined somewhere else. It took me hours to get this to work, so to save you the time, here is the solution:
fields = ['field_a', 'field_b', 'field_c']
# the base model with some basic fields
class MyModel(models.Model):
date = models.DateField()
# add the extra fields after the model has been created
for field in fields:
MyModel.add_to_class(field, models.DecimalField(decimal_places=4, max_digits=10))
My first instinct was to create an __init__ function inside the model class and use that to create the extra fields, but since the __init__ function is never called for models, this didn’t work. Creating the extra fields after you created the model class itself however works just fine.
Written by
Kevin Renskers
I'm a freelance software developer with over 25 years of experience. I write articles about Swift, Python, and TypeScript. I've worked on many apps, and maintain a bunch of open source projects. I'm available for hire and for podcast interviews about modern web development. Connect with me on Mastodon or email.