整体开发流程:
1.在数据库中建表
2.利用ORM生成对应的模型,并对模型做适当调整
3.在app的urls.py中添加路由
4.在views.py中添加视图函数(需要配置djangorestframework)
5.编写序列化器
6.请求
7.添加缓存
下面通过一个案例详细讲解上面的过程:
1.在数据库中建表
-- 创建地区表tb_district
create table `tb_district`
(
`distid` int not null comment '编号',
`pid` int comment '父级行政单位',
`name` varchar(255) not null comment '名称',
`ishot` bool default 0 comment '是否为热门城市',
`intro` varchar(255) default '' comment '介绍',
primary key (distid)
);
结果如下:
在表中插入相关数据(数据地址如下:https://gitee.com/ms-hou/mysite/blob/master/insert_data.sql,为了演示方便,只插入了少数地址–北京市、天津市和河北省)
2.利用ORM,将表变模型
执行下面的命令:
python manage.py inspectdb > api/models.py
将表变模型的结果重定向到api/models.py 文件中
自动生成的模型代码如下:
from django.db import models
class TbDistrict(models.Model):
distid