◆ ORM定义:
Object Relational Mapping 对象关系映射,是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换 。从效果上说,它其实是创建了一个可在编程语言里使用的–“虚拟对象数据库”。
◆ 对应关系:
models.tb.objects.filter(id_gt=1)
models.tb.objects.filter(id=1)
models.tb.objects.filter(id_lt=1)
◆ 创建类:
app下的models.py编写类(注:会根据类在数据库中自动创建表)
from django.db import models
默认表名 app01_userinfo
class UserInfo(models.Model):
#用户名列,字符串类型,指定长度
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
◆ 注册APP和驱动:
settings:
DATABASES = {
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME':'***',
'USER':'***',
'PASSWORD':'***',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01'
]
◆ 创建数据库对应表:
1、执行 python manage.py makemigrations
>python manage.py makemigrations
Migrations for 'slave':
slave\migrations\0001_initial.py
- Create model Warn_Incidnet
2、执行 python manage.py migrate
>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, slave
Running migrations:
Applying slave.0001_initial... OK
◆ 使用MySQL数据库:
Django默认使用MySQLdb模块连接MySQL。如需使用pymsql,在project同名文件夹下得inint文件夹中添加如下代码即可
import pymysql
pymysql.install_as_MySQLdb()