Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django create db table headers from dict

I am trying to create a model.Model with the columnheaders(key) and types(value). I tried it with the setattr(self,columnheader,columntype) but this seems to not work. Can i dynamically alter the table with django inbuilts or do i have to use raw sql?

Example dict:

_dict = { "column_1": models.IntegerField(),
"column_2": models.IntegerField()
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can assign this to the local variables, but I would advise against this:

_dict = {
    'column_1': models.IntegerField(),
    'column_2': models.IntegerField()
}

class MyModel(models.Model):
    locals().update(_dict)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading