This works fine, however if I try to change the db_table again to a different table (keep in mind, these are two different tables in the same database), it errors out. It doesn’t run the query, but if I switch back to the first one it works fine.
How can I dynamically switch the db_table I’m querying?
Create a second model to reference the second table. It’s really going to be easier that way.
If there are a lot of fields that you don’t want replicated in your file, then create an abstract model for the structure and two different models to inherit from it, each with a different Meta class to specify the table being referenced.
Note: Because Django runs in a multi-process / multi-threaded environment and these models are Module level classes that are registered in Django at start-up, you do not want to try and modify them dynamically.
The problem with that is that while there are two tables now, there might be more in the future. Think of 5 new tables a day or something. This might kinda be a problem. Is there any other way I can query the different databases? Like changing the queryset or something?
First, different databases is a separate topic from different tables in a database. Just to confirm, we’re talking about multiple tables in one database, correct?
If so, then no. The Django ORM is not designed to facilitate that type of dynamic table access.
The Django ORM is a very intricate set of code. The models you define in your models.py file aren’t really the classes being used. There’s a lot of metaclass programming that occurs to build the actual models used by Django when accessing the database. And again, as module-level classes, modifying them becomes a global change across the process - and would not apply between processes in a production-quality deployment.
You might be able to build a metaclass capable of dynamically building new models outside of Django’s normal startup, but that would be well beyond anything I’ve ever attempted - and again, something that would need to be managed across multiple processes and process restarts.