上一節項目框架已經搭建完畢,如今開始鏈接數據庫,建立modelpython
一、數據庫設置
python默認安裝了sqlite數據庫mysql
打開文件:dayang/settings.pysql
ENGINE – 數據庫引擎數據庫
'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', 'django.db.backends.oracle'.
NAME – 數據庫的名字django
小貼士:若是你選擇sqlite,數據庫是以文件的形式生成,name要設置成絕對路徑session
By default, INSTALLED_APPS contains the following apps, all of which come with Django:oracle
django.contrib.admin – The admin site. You’ll use it shortly.app
django.contrib.auth – An authentication system.框架
django.contrib.contenttypes – A framework for content types.ide
django.contrib.sessions – A session framework.
django.contrib.messages – A messaging framework.
django.contrib.staticfiles – A framework for managing static files.
These applications are included by default as a convenience for the common case.
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:
manage.py migrate # 建立表結構
二、建立模型
三、激活模型
That small bit of model code gives Django a lot of information. With it, Django is able to:
Create a database schema (CREATE TABLE statements) for this app.
Create a Python database-access API for accessing Question and Choice objects.
But first we need to tell our project that the polls app is installed.
執行命令:manage.py makemigrations polls
# 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.
執行成功後目錄結構以下圖:
Now, run migrate again to create those model tables in your 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 changesRun python manage.py migrate to apply those changes to the database.