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.

  • makemigration - This command is used to create a migration file that contains code for the tabled schema of a model.
  • migrate - This command creates a table according to the schema defined in migration file
  • sqlmigrate - This command is used to show a RAW SQL query of the applied migration.
  • showmigrations - This command list all the migrations and their status.

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 makemigrations

After creating a migration, to reflect changes in the database permanently execute migrate command -

$ python3 manage.py migrate

To 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 blog

To see all migrations, execute the command -

$ python3 manage.py showmigrations


Discussion

No Comment Found