Django create table

Prerequisites

Django Model

  • A Django model is a ORM representation of database table.
  • Model communicates with the database and returns the data in the form of python objects.

Create django model - Contact

  • use the code from Django create app
  • open the file my_app/models.py and update the code as below.

my_app/models.py

from django.db import models

class Contact(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(max_length=255)
    phone = models.CharField(max_length=10, null=True)

    class Meta:
        db_table = "contact"

Create model migrations

  • To create database migrations for the table run command python manage.py makemigrations my_app -n "contact_table" where my_app is the app name.
  • It will create the migration file my_app/migrations/0001_contact_table.py.
  • The migration file looks like below.

my_app/migrations/0001_contact_table.py

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name="Contact",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("first_name", models.CharField(max_length=30)),
                ("last_name", models.CharField(max_length=30)),
                ("email", models.EmailField(max_length=255)),
                ("phone", models.CharField(max_length=10, null=True)),
            ],
            options={
                "db_table": "contact",
            },
        ),
    ]
  • By default, django create a primary key with column id and which is auto incremented, unless we specify a foreign key.

Get SQL from django migration

  • Django management command also provides a way to see the SQL before applying the migration.
  • To see the SQL of the migration, run command python manage.py sqlmigrate my_app 0001_contact_table where my_app is app name and 0001_contact_table is migration name.
  • Once we run the command it shows the SQL as below.
BEGIN;
--
-- Create model Contact
--
CREATE TABLE "contact" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "email" varchar(255) NOT NULL, "phone" varchar(10) NULL);
COMMIT;

Check for unapplied migrations

  • When we run the development server with command python manage.py runserver django displays the unapplied migrations like in the below image.

Django unapplied migrations

  • The other way is to use the command python manage.py showmigrations. It will show the apps and their migrations if applied it will check the box otherwise shows the unchecked box to the migration name.

Apply unapplied migrations

  • To apply all migrations at once just run command python manage.py migrate
  • To apply a migrations related a sinle app then run command python manage.py migrate my_app
  • To apply a specific migration of an app then run command python manage.py migrate my_app 0001_contact_table
  • For now, just apply all migrations at once.

Note: my_app -> app name, 0001_contact_table is migration name

Check if table is created

  • By default, the django is configured to use sqlite3 database.
  • Install the free sqlite db viewer from https://sqlitebrowser.org/dl/
  • Open the db.sqlite3 file with sqlite db viewer then you will be able see something like below image.

SQLite3 tables

  • Can also be checked from django shell
    • Run the command python manage.py shell
    • Import the model from my_app.models import Contact
    • Create a contact Contact.objects.create(first_name="John", last_name="D", email="[email protected]")
    • It will create contact in the database.

References: