上一节项目框架已经搭建完毕,现在开始连接数据库,创建model

1、数据库设置
python默认安装了sqlite数据库

打开文件:dayang/settings.py

clipboard.png

ENGINE – 数据库引擎

     'django.db.backends.sqlite3', 
     'django.db.backends.postgresql', 
     'django.db.backends.mysql',
     'django.db.backends.oracle'.

NAME – 数据库的名字

小贴士:如果你选择sqlite,数据库是以文件的形式生成,name要设置成绝对路径

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.

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 # 创建表结构
clipboard.png

2、创建模型

clipboard.png

3、激活模型
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.

clipboard.png

执行命令: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.

clipboard.png

执行成功后目录结构如下图:

clipboard.png

clipboard.png

Now, run migrate again to create those model tables in your database:

clipboard.png

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.


轩雪初晨
64 声望3 粉丝