Dynamic Models in Django

In this article, we will learn how to connect external databases in Django and make a dynamic model for multiple tables in the database.

Models in Django

A Django model contains essential fields and behaviors of the data stored in the database. It is a definitive source of information about your data. Each model maps to a single database table.

  • Each model is a Python class that sub-classes¬†django.db.models.Model.
  • Each attribute of the model represents a database field.
  • With all of this, Django gives you an automatically generated database access API.

Now, what if you are required to use a single model for multiple databases…

Need for dynamic models

Let’s assume you are working with an external database, where their 100s of tables with the same fields and names changing according to any parameter. Ex: exam2021, exam2020, exam2019 here table name changes with respect to the session, and the exam tables have the same fields but, different data.

Now, hard coding different models for each table will the make code redundant and big, and using a dynamic model will be a better idea.

Let’s first understand how to connect the external database.

Connecting external database

To keep the password and other important information hidden we can use .env file  variables in Django settings using decoulple.config.

When connecting external databases we are required to make models for the respective tables in the database, we keep “managed” in the meta class of each table false because the table is already there, we just need a schema to access it.

Dynamic models

Now, there are 100s of tables with different names (deductible through code) but, the same schema. So, we will be making a dynamic model which can be used with each table with the same schema.

Let’s take the example of exam tables in a school i.e… exam2021, exam2020, exam2019, etc here name changes wrt to the session, and the table name comes out to be “exam + current_session”


  • Single model for every table
  • Changing table wrt actual table
  • Making code less redundant

Dynamic model

For the dynamic model, we are using a function in which we will send the current session. Whenever, the function is called a model with various fields such as subjectcode, subject_name, etc will be formed which will be in the actual database table. The table name will be generated in meta class using the db_table attribute which will set the table name to ‘exam’ + session, managed=False is set because we have a table already, we just need to access its data.

After the creation of the class whole class will be returned which can be used as and normal class.

This object will have a class for table “exam2022” in the database, we can use it to perform actions on “exam2022”