Use the same model to query two identical tables.

I have a model, and two identical tables. These tables are part of an external database which I have no control over.

I am using django rest framework to allow users to select which table they want to query.

class ReportCalendar(models.Model):
    calendar_id = models.TextField(db_column="CALENDAR_ID", blank=True, primary_key=True)

    class Meta:
        managed = False

Now, what I am currently doing is this:

ReportCalendar._meta.db_table = users_selected_table
return ReportCalendar.objects.all()

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.

It really is going to be easier this way.

Thanks for your quick reply Ken.

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?

Thanks again.

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.

Another alternative would be to build all your queries using raw sql in a manager for that model.