I am attempting to create tables with fields based on metadata declared on other classes. My current approach is a bit like this:
metadata = { ... }
class CustomModel(MyBaseModel):
field1 = CharField(...)
field2 = CharField(...)
...
for key, info in metadata.items():
setattr(CustomModel, key, fieldFrom(info))
What currently happens is that the table is created and the fields declared in class included in the migration.
BUT the fields included through setattr are not getting included in the migration, even tough they correctly appear in the class when inspecting with the debugger. Is there any magic that only works for fields declared “in-place”? How could I dynamically set those fields?
EDIT: The models are still static. The gist here is that when I make changes to source metadata, those changes would propagate to (i.e.) several models and/or fields. Without this, I'd have to exhaustively add fields to several models manually.
EDIT2:
I'm gonna hand an example that is not really my current case but also applies. Imagine I had an openAPI (swagger) file somewhere inside my project and I wanted to dynamically create tables based on its definitions key. This should be no big deal, right?
This swagger.json file would be static. Whenever I made changes to it, I'd run makemigrations and it would add the necessary changes to my DB.
(Now please, don't come with "but you shouldn't be creating data from a swagger.json", this is not the focus of my question -- and this is even a fictional example. I didn't ask for architecture advice, thank you!)
makemigrationscommand and thenmigrate. If you want to dynamically change model fields, you would need to find a way to dynamically generate and apply migrations as well. This feels dangerous and fragile. You might want to consider just how badly do you want to do this.