InterviewSolution
| 1. |
How to do migrations in Django |
|
Answer» To manage database schema changes migrations are a great way. You will find Django has created migration files inside the migration folder for each model. Each table is mapped to the model. Django has various commands to perform migration-related tasks. After CREATING models you can use these commands.
We have a model with attributes as given below - //models.py from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) TEXT = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) class Meta: db_table = "blog"LET US create a migration for this model, use the below command and it will create a migration file inside the migration folder. $ python3 manage.py makemigrationsAfter creating a migration, to reflect changes in the database permanently execute migrate command - $ python3 manage.py migrateTo see raw SQL query executing behind applied migration execute the command - $ sqlmigrate app-name migration-name (for example sqlmigrate blog 001)To see app-specific migrations by specifying app-name, execute the command - $ python3 manage.py showmigrations blogTo see all migrations, execute the command - $ python3 manage.py showmigrations |
|