模型类和数据库有关系
模型类和数据库有关系
class 类名:
xxx =
xxx1 =
通过一种手段 把类名 当做表名、 把这个属性当做字段名字
这个手段叫ORM
O :object 对象
R: relation 关系
M: mapping 映射
ORM的作用就是把类转成SQL语句、可以把SQL语句转成类
减少开发时间
CharField 对应到数据库的字符串
IntegerField 对应到数据库的整数
django 有个数据库 sqlite
sqlite是小型关系数据库
迁移由两步完成:
1)python manage.py makemigrations 生成迁移文件:
2)python manage.py migrate 迁移
要把迁移文件生成数据库表
可能出现错误:No changes detected 没有可生成的东西
1、看下模型类写没写
2、看下应用是否注册
![](https://img.haomeiwen.com/i20424102/bde08a6d01688d71.png)
每个应用文件事先都要注册应用
![](https://img.haomeiwen.com/i20424102/183e402531356e32.png)
![](https://img.haomeiwen.com/i20424102/0e06366aeabda12d.png)
![](https://img.haomeiwen.com/i20424102/d67453fe0fb1b379.png)
模型类自带主键---上图的id那一行
默认的表名 应用名+模型类名字转小写
![](https://img.haomeiwen.com/i20424102/2a5bd7c767b9c436.png)
python manage.py shell
创建完记得保存
这个save方法相当于把这个数据执行了insert
![](https://img.haomeiwen.com/i20424102/7dc706e89e537f23.png)
查询: select
Hero.objects.all()相当于 select * from xxxx
Hero.objects.filter(id=1) 相当于 select * from xxx where id =1
![](https://img.haomeiwen.com/i20424102/97d9ac240b13fe06.png)
更新、修改
![](https://img.haomeiwen.com/i20424102/ed8ee6586dd17b54.png)
![](https://img.haomeiwen.com/i20424102/cc748e4740ff9b95.png)
删除
![](https://img.haomeiwen.com/i20424102/c07df28f24295d4e.png)
![](https://img.haomeiwen.com/i20424102/1fe7ca3f087a90f1.png)
视图view
处理业务逻辑的
写视图的时候,千万不要忘记写路由
![](https://img.haomeiwen.com/i20424102/f5f2505b2639bfc4.png)
![](https://img.haomeiwen.com/i20424102/5bc8cc9e33dde618.png)
python manage.py runserver 8001 运行起来
效果:
![](https://img.haomeiwen.com/i20424102/7745adfbba790938.png)
![](https://img.haomeiwen.com/i20424102/68909e7b1d7a9a92.png)
templates模板
写模板的时候千万不要忘记注册模板
![](https://img.haomeiwen.com/i20424102/65edd69969f9b45a.png)
![](https://img.haomeiwen.com/i20424102/36b09959b53cd870.png)
![](https://img.haomeiwen.com/i20424102/ade00826a1dd0024.png)
![](https://img.haomeiwen.com/i20424102/a940e7b9b9947e18.png)
浏览器--->路由---->视图---->模型--->模板(模板语言)
![](https://img.haomeiwen.com/i20424102/c6ac8e6c32f746e7.png)
模板语言把数据解析出来
多个数据要循环遍历
取值用大括号{}
<ul>
{%for hero in heros %}
<li>{{hero.name }}</li>
{%endfor %}
</ul>
![](https://img.haomeiwen.com/i20424102/3b94e5a56a1049ce.png)
![](https://img.haomeiwen.com/i20424102/f8d6b1ebf2643c8b.png)
给技能表添加数据:
![](https://img.haomeiwen.com/i20424102/d0303d132b8ccafd.png)
![](https://img.haomeiwen.com/i20424102/a7dbfe88dc008e60.png)
解决404错误:
![](https://img.haomeiwen.com/i20424102/a6c7f1a9eb42c9f8.png)
![](https://img.haomeiwen.com/i20424102/8e1d301915261c7b.png)
![](https://img.haomeiwen.com/i20424102/8965cdd9ab3e061e.png)
![](https://img.haomeiwen.com/i20424102/80a3a762d2ae3120.png)
视图:
def show(request,id):
hero=Hero.objects.filter(id=id).first()
if not hero:
raise Http404()#抛出异常
else:
#一查多
kills = hero.kill_set.all()#kills = Kill.objects.filter(hero_id=id).all()
return render(request,'Kills.html',locals())