django学习笔记【003】创建第一个带有model的app

时间:2023-03-09 23:13:58
django学习笔记【003】创建第一个带有model的app

【1】python应用程序要连接mysql有多个驱动程序可供选择:

  1、MySQLdb 这个只支持python2.x 所以在这里就不说了;

  2、mysqlclient 下载地址  

https://pypi.python.org/pypi/mysqlclient/1.3.9

  3、MySQL Connector/python 这个是mysql官方主推的mysql驱动

https://dev.mysql.com/downloads/connector/python/

  从django的官方文档中没有找到为什么python3.x选择了mysqlclient而不是MySQL Connector/Python ;在编写用到数据库功能的Django之前

  要把mysqlclient安装一下。

  

【2】把polls这个app注册到project中去、修改settings.py 文件的INSTALLED_APPS配置项

INSTALLED_APPS = [
'polls.apps.PollsConfig', # 增加polls.apps.PollsConfig 用于注册polls到project
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

【3】配置django连接mysql数据库的方式、修改settings.py 文件的DATABAES配置项

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'tempdb',
'USER': 'appuser',
'PASSWORD': 'helloapp',
'HOST': '127.0.0.1',
'PORT': ''
}
}

【4】创建模式、在polls/models.py 文件下增加如下orm类

from django.apps import AppConfig

class PollsConfig(AppConfig):
name = 'polls'

【5】创建用于迁移的中间文件

tree polls/
polls/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│   └── __init__.py
├── models.py
├── tests.py
└── views.py python3.5 manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Person tree polls/
polls/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│   ├── 0001_initial.py
│   ├── __init__.py
│   └── __pycache__
│   └── __init__.cpython-35.pyc
├── models.py
├── __pycache__
│   ├── admin.cpython-35.pyc
│   ├── apps.cpython-35.pyc
│   ├── __init__.cpython-35.pyc
│   └── models.cpython-35.pyc
├── tests.py
└── views.py

【6】把迁移应用到数据库

python3. manage.py migrate polls
Operations to perform:
Target specific migration: 0001_initial, from polls
Running migrations:
Applying polls.0001_initial... OK

【7】查看数据库中有哪些变更

show tables;
+-------------------+
| Tables_in_tempdb |
+-------------------+
| django_migrations |
| polls_person |
+-------------------+ show create table polls_person;
+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| polls_person | CREATE TABLE `polls_person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(8) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+

----