python第三方库之Django学习笔记二

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

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

打开文件:dayang/settings.py

《python第三方库之Django学习笔记二》

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 # 创建表结构
《python第三方库之Django学习笔记二》

2、创建模型

《python第三方库之Django学习笔记二》

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.

《python第三方库之Django学习笔记二》

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

《python第三方库之Django学习笔记二》

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

《python第三方库之Django学习笔记二》

《python第三方库之Django学习笔记二》

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

《python第三方库之Django学习笔记二》

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.

    原文作者:轩雪初晨
    原文地址: https://segmentfault.com/a/1190000010963922
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞