How to create VIEWS using Django Migrations?

Photo by Faisal on Unsplash

How to create VIEWS using Django Migrations?

Table of contents

No heading

No headings in the article.

This post assumes that you know what views are, if not please read here: Database Views

Let's start with the 'why'!

Once upon a time, our product team came up with a request, they wanted us to create VIEWS so that they can use those VIEWS for making custom dashboards (metabase) for the users.

We did not want to go and change our prod Databases directly, running an SQL query there was not an option, we wanted to do it programmatically via Django so I started on my journey to find an elegant solution.

While searching for a solution I came across on how one can use Django Migrations to create VIEWS.

Let us see how it is done!

  • Create an empty migration file in the Django app
python manage.py makemigrations --name <migration_name> <app_name> --empty

You can choose to custom name your migration or you can let Django create an empty migration with the default naming convention by omitting the --name tag.

Your empty migration file will look like this:

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0001_initial'),
    ]

    operations = [
    ]
  • Write the SQL for the creation of your VIEW

Django migrations framework lets you run raw SQL

In the operations field, add your SQL query for creating the VIEW

operations = [
      migrations.RunSQL('SQL for the View you want to create')
    ]

You can find more information about running Raw SQL using Django migrations here

  • Run the migrate command

Now you need to run the migrate command and your VIEW will be created in your db.

python manage.py migrate

et voila!

Congratulations on reaching the end of this article, now that you know how to create VIEWS using Django migrations go berserk and experiment, but only on your local test env. ;)

Thanks for reading, stay tuned for more such knowledge bombs.