Site icon Tutorial

Installing the Model

We’ve written the code; now let’s create the tables in our database. In order to do that, the first step is to activate these models in our Django project. We do that by adding the books app to the list of installed apps in the settings file. Edit the settings.py file again, and look for the INSTALLED_APPS setting. INSTALLED_APPS tells Django which apps are activated for a given project. By default, it looks something like this:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

To register our “books” app, add ‘books.apps.BooksConfig’ to INSTALLED_APPS, so the setting ends up looking like this:

       INSTALLED_APPS = [
'books.apps.BooksConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Each app in INSTALLED_APPS is represented by its full Python path – that is, the path of packages, separated by dots, leading to the app package. The dotted path in this case points to the BooksConfig class that Django created for you in the apps.py file. Well will look at app configurations in more detail later in the book.

Now that the Django app has been activated in the settings file, we can create the database tables in our database. First, let’s validate the models by running this command:

python manage.py check

The check command runs the Django system check framework – a set of static checks for validating Django projects. If all is well, you’ll see the message System check identified no issues (0 silenced). If you don’t, make sure you typed in the model code correctly. The error output should give you helpful information about what was wrong with the code. Any time you think you have problems with your models, run python manage.py check. It tends to catch all the common model problems.

If your models are valid, run the following command to tell Django that you have made some changes to your models (in this case, you have made a new one):

  python manage.py makemigrations books

You should see something similar to the following:

Migrations for 'books':
0001_initial.py:
- Create model Author
- Create model Book
- Create model Publisher
- Add field publisher to book

Migrations are how Django stores changes to your models (and thus your database schema) – they’re just files on disk. In this instance, you will find a file names 0001_initial.py in the \migrations folder of the books app. The migrate command will take your latest migration file and update your database schema automatically, but first, let’s see what SQL that migration would run. The sqlmigrate command takes migration names and returns their SQL:

python manage.py sqlmigrate books 0001

You should see something similar to the following (reformatted for readability):

BEGIN;
CREATE TABLE "books_author" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(40) NOT NULL,
"email" varchar(254) NOT NULL
);
CREATE TABLE "books_book" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" varchar(100) NOT NULL,
"publication_date" date NOT NULL
);
CREATE TABLE "books_book_authors" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"book_id" integer NOT NULL REFERENCES "books_book" ("id"),
"author_id" integer NOT NULL REFERENCES "books_author" ("id"),
UNIQUE ("book_id", "author_id")
);
CREATE TABLE "books_publisher" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" varchar(30) NOT NULL,
"address" varchar(50) NOT NULL,
"city" varchar(60) NOT NULL,
"state_province" varchar(30) NOT NULL,
"country" varchar(50) NOT NULL,
"website" varchar(200) NOT NULL
);
CREATE TABLE "books_book__new" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" varchar(100) NOT NULL,
"publication_date" date NOT NULL,
"publisher_id" integer NOT NULL REFERENCES
"books_publisher" ("id")
);

INSERT INTO "books_book__new" ("id", "publisher_id", "title",
"publication_date") SELECT "id", NULL, "title", "publication_date" FROM
"books_book";

DROP TABLE "books_book";

ALTER TABLE "books_book__new" RENAME TO "books_book";

CREATE INDEX "books_book_2604cbea" ON "books_book" ("publisher_id");

COMMIT;

Note the following:

These CREATE TABLE statements are tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key (SQLite) are handled for you automatically. The same goes for quoting of column names (e.g., using double quotes or single quotes). This example output is in PostgreSQL syntax.

The sqlmigrate command doesn’t actually create the tables or otherwise touch your database – it just prints output to the screen so you can see what SQL Django would execute if you asked it. If you wanted to, you could copy and paste this SQL into your database client, however Django provides an easier way of committing the SQL to the database: the migrate command:

python manage.py migrate

Run that command, and you’ll see something like this:

Operations to perform:
Apply all migrations: admin, auth, books, contenttypes, sessions
Running migrations:
Applying books.0001_initial... OK

In case you get a bunch of extra migrations, this is most likely because you forgot to run the initial migrations. The first time you run migrate, Django will also create all the system tables that Django needs for the inbuilt apps.

Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, however there are some caveats.

Back to Tutorial

Exit mobile version