Writing your first Django app, part 2
Database setup
Now, open upmysite/settings.py
.By default, the configuration uses SQLite. SQLite is included in Python, so you won’t need to install anything else to support your database while starting your first real project .
If you wish to use another database, install the appropriate database and change the following keys in the
DATABASES
'default'
item to match your database connection
settings:ENGINE
– Either'django.db.backends.sqlite3'
,'django.db.backends.postgresql'
,'django.db.backends.mysql'
, or'django.db.backends.oracle'
. Other backends are also available.NAME
– The name of your database. If you’re using SQLite, the database will be a file on your computer; in that case,NAME
should be the full absolute path, including filename, of that file. The default value,os.path.join(BASE_DIR, 'db.sqlite3')
, will store the file in your project directory.
USER
, PASSWORD
, and HOST
must be added.This example is for PostgreSQL:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
ENGINE
¶
The database backend to use. The built-in database backends are:
'django.db.backends.postgresql'
'django.db.backends.mysql'
'django.db.backends.sqlite3'
'django.db.backends.oracle'
mysite/settings.py
, set TIME_ZONE
to
your time zone.Also, note the
INSTALLED_APPS
setting at the top of the file. That
holds the names of all Django applications that are activated in this Django
instance .ute them for use by others in their projects.
By default,
INSTALLED_APPS
contains the following apps, all of which
come with Django:django.contrib.admin
– The admin site. You’ll use it shortly.django.contrib.auth
– An authentication system.django.contrib.contenttypes
– A framework for content types.django.contrib.sessions
– A session framework.django.contrib.messages
– A messaging framework.django.contrib.staticfiles
– A framework for managing static files.
Some of these applications make use of at least one database table, though, so we need to create the tables in the database before we can use them. To do that, run the following command:
$ python manage.py migrate
migrate
command looks at the INSTALLED_APPS
setting
and creates any necessary database tables according to the database settings
in your mysite/settings.py
file .Note :The
migrate
command will only run migrations for apps in
INSTALLED_APPS
.Creating models :
Now we’ll define your models – essentially, your database layout, with additional metadata.A model contains the essential fields and behaviors of the data you’re storing .
In our simple poll app, we’ll create two models:
Question
and Choice
.
A Question
has a question and a publication date. A Choice
has two
fields: the text of the choice and a vote tally. Each Choice
is associated
with a Question
.These concepts are represented by simple Python classes. Edit the
polls/models.py
file so it looks like this:
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Activating models
First we need to tell our project that the
polls
app is installed.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.INSTALLED_APPS = [ 'polls.apps.PollsConfig',
]
Now Django knows to include the
polls
app. Let’s run another command:$ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to 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 just files on disk .
Note the following:
Table names are automatically generated by combining the name of the app
(
polls
) and the lowercase name of the model – question
and
choice
. (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 KEY
constraint
The
sqlmigrate
command doesn’t actually run the migration on your
database - it just 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.$ python manage.py sqlmigrate polls 0001
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.
migrate
again to create those model tables in your database:$ python manage.py migrate
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. remember the three-step guide to making model changes:
- Change your models (in
models.py
). - Run
python manage.py makemigrations
to create migrations for those changes - Run
python manage.py migrate
to apply those changes to the database.
0 comments:
Post a Comment