多表操作准备工作
settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'orm1', "USER":'root', 'PASSWORD':'123456', 'HOST':'127.0.0.1', 'PORT':3306, 'CHARSET':'utf8', } }
init.py
import pymysql pymysql.install_as_MySQLdb()
models.py
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=8,decimal_places=2) publish_date = models.DateField(auto_now_add=True) # 一对多 publishs = models.ForeignKey(to='Pulish') # 多对多 authors = models.ManyToManyField(to='Author') class Pulish(models.Model): name = models.CharField(max_length=32) addr = models.CharField(max_length=64) email =models.EmailField() # varchar(254) 该字段类型不是给models看的,而是给校验性组件看的 class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() # 一对一 author_detail = models.OneToOneField(to='AuthorDetail') class AuthorDetail(models.Model): phone = models.BigIntegerField() # 电话号码用BigIntergerField或者直接用CharField addr = models.CharField(max_length=64)
Terminal
python manege.py makegirations python manage.py migrate
生成的表格(为了简便,数据直接用Navicat手动输入)
app01_author表 :
| id | name | age | author_detail_id |
|---|---|---|---|
| 1 | Kevin | 18 | 1 |
| 2 | Steven | 20 | 2 |
| 3 | Adam | 28 | 3 |
| app01_authordetail表 : | |||
| id | phone | addr | |
| – | – | – | – |
| 1 | 100 | 南京 | |
| 2 | 200 | 北京 | |
| 3 | 300 | 深圳 | |
| app01_pulish表 : | |||
| id | name | addr | |
| – | – | – | – |
| 1 | 东方出版社 | 东方 | 123@qq.com |
| 2 | 西方出版社 | 西方 | 666@qq.com |
