Activating models
That small bit of model code gives Django a lot of information. With it, Django is able to:
- Create a database schema (
CREATE TABLEstatements) for this app. - Create a Python database-access API for accessing
QuestionandChoiceobjects.
But first we need to tell our project that the polls app is installed.
Philosophy
Django apps are “pluggable”: You can use an app in multiple projects, and you can distribute apps, because they don’t have to be tied to a given Django installation.
To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this:
mysite/settings.py¶INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Now Django knows to include the polls app. Let’s run another command:
$ python manage.py makemigrations polls
You should see something similar to the following:
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Question
- Create model Choice
By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
Migrations are how Django stores changes to your models (and thus your database schema) - they’re files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.
There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and we’ll come to it in a moment - 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 polls 0001
You should see something similar to the following (we’ve reformatted it for readability):
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
"id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL,
"question_id" bigint NOT NULL
);
ALTER TABLE "polls_choice"
ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
Note the following:
- The exact output will vary depending on the database you are using. The example above is generated for PostgreSQL.
- Table names are automatically generated by combining the name of the app (
polls) and the lowercase name of the model –questionandchoice. (You can override this behavior.) - Primary keys (IDs) are added automatically. (You can override this, too.)
- By convention, Django appends
"_id"to the foreign key field name. (Yes, you can override this, as well.) - The foreign key relationship is made explicit by a
FOREIGN KEYconstraint. Don’t worry about theDEFERRABLEparts; it’s telling PostgreSQL to not enforce the foreign key until the end of the transaction. - It’s tailored to the database you’re using, so database-specific field types such as
auto_increment(MySQL),bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY(PostgreSQL), orinteger primary key autoincrement(SQLite) are handled for you automatically. Same goes for the quoting of field names – e.g., using double quotes or single quotes. - The
sqlmigratecommand doesn’t actually run the migration on your database - instead, it prints it to the screen so that you can see what SQL Django thinks is required. It’s useful for checking what Django is going to do or if you have database administrators who require SQL scripts for changes.
If you’re interested, you can also run python manage.py check; this checks for any problems in your project without making migrations or touching the database.
Now, run migrate again to create those model tables in your database:
$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Rendering model states... DONE Applying polls.0001_initial... OK
The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.
Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:
- Change your models (in
models.py). - Run
python manage.py makemigrationsto create migrations for those changes - Run
python manage.py migrateto apply those changes to the database.
The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also usable by other developers and in production.
Read the django-admin documentation for full information on what the manage.py utility can do.