How to create VIEWS using Django Migrations?

Search for a command to run...

One of the methods of abstraction is to integrate another service. But can you trust someone else's service? Third-party APIs are notorious for failing at the worst possible time. Over time, I ended u

A race condition can hit you anytime, you think it won't because your system isn't that big, or doesn't process a lot of requests, but it will happen, and when it happens, you will feel a bit silly ab

The world is going through a tumultuous phase, but that doesn't stop the progress of humanity. Things go on, people move, prices fluctuate, we eat fruit and live a healthy life. April is hot, so hot,

Well, I celebrated my birthday. :P I worked on a functionality end to end using AI. It was a simple feature and AI wrote everything correctly in a single pass. I used Codex. After that, I had to ask i

Let me think. So I worked on a new functionality and raised a PR in just 2 days for the whole end-to-end correct flow. I did not focus much on performance because I wanted to first get it right and th

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!
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 = [
]
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
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.