I'd like to enable the feature of dynamically changing `models.py` in my project.

Hello, I’d like to enable the feature of dynamically changing models.py in my project. However, when I thought everything was fine, I encountered the following error message:

“Cannot query “table_model_001 object (1)”: Must be “table_model_001” instance.”

Here are the steps I followed:

  1. Used a function in views.py to modify models.py.
  2. Attempted to update the model stored in the application simultaneously, using “type(model_name, (instance_model,), attrs)”.
  3. Ran makemigrations: “call_command(‘makemigrations’, ‘app_name’)”.
  4. Ran migrate: “call_command(‘migrate’, app_label=‘app_name’)”.
  5. Tried to delete data and received the error message: “omdata_model.objects.filter(data_no=data_no).delete()”.

I would like to know if Django supports such functionality or if there is an error in my steps. Thank you.

This isn’t something Django supports, not really.

Models are (just) Python classes, so you can in theory construct them at runtime, but syncing to the DB, and … — No.

There’s a page on the Django Wiki about it from the 0.96 days but I can’t say what it would take to get it going in a modern Django.

Searching for that wiki page turned up this Reddit comment:

Is it possible? yes. is it easy? no. is it wise? very much no.

That seems about right to me.

1 Like

I sometimes do this when I just want a nice class to capture my raw sql for reporting… One day I might propose that we allow a “lightweight model for read-only raw sql” formally because it will break strict tests that error on warning and this approach will raise duplicate registration warnings.

But as Carlton mentioned… yeah you want static models if you need any kind of schema syncing to the db.

2 Likes

@shangxiao Can I ask when you’d do that rather than say use a view (with a managed=False model)?

It is possible to implement dynamic (on the fly) models with Django but it is not trivial. We do this in Baserow. If you really need it you can look at How Baserow lets users generate Django models on the fly // Baserow and Baserow backend codebase.

That being said, most likely you don’t actually need it and should think harder about your schema.

2 Likes

@stribny I’d forgotten that post — thanks for the reminder!