1、引入数据模块
from models import BlogModel
- 1
2、利用模型创建数据
blogModel = BlogModel(title='我是第一篇文章标题',content='我是第一篇文章的内容')
- 1
3、利用
save
方法提交到数据库blogModel.save()
- 1
4、完整代码
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import BlogModel def index(request): blogModel = BlogModel(title='我是第一篇文章标题',content='我是第一篇文章的内容') blogModel.save() return render(request,'book_index.html',{'msg':'HELLO WORD'})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
二、查询所有数据
- 1、引入数据模型
2、利用
objects
查询数据.all()
返回的是一个list
数据blogModel = BlogModel.objects.all()
- 1
3、完整代码
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import BlogModel def index(request): blogModel = BlogModel.objects.all() print '*'*100 print blogModel print '*'*100 return render(request,'book_index.html',{'msg':'HELLO WORD'})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
三、查询第一条数据(在查询所有的基础上下first
)返回的数据是一个object
1 完整代码
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import BlogModel def index(request): blogModel = BlogModel.objects.all().first() print '*'*100 print blogModel print '*'*100 return render(request,'book_index.html',{'msg':'HELLO WORD'})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
四、根据id
查询数据(利用get(条件)
)返回的也是一个object
1、完整代码
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import BlogModel def index(request): blogModel = BlogModel.objects.get(id=1) print '*'*100 print blogModel print '*'*100 return render(request,'book_index.html',{'msg':'HELLO WORD'})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
五、删除数据(返回的是删除的这条数据)
- 1、先利用上面的方式查询到数据
- 2、利用
delete
删除查询到的这条数据 3、完整代码
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import BlogModel def index(request): blogModel = BlogModel.objects.get(id=1) aa = blogModel.delete() return render(request,'book_index.html',{'msg':'HELLO WORD'})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
六、修改数据
- 1、先查询数据
- 2、重新给字段赋值
- 3、提交数据
4、完整代码
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import BlogModel def index(request): blogModel = BlogModel.objects.get(id=2) blogModel.title = '我修改后的数据' blogModel.content = '文章内容' blogModel.save() return render(request,'book_index.html',{'msg':'HELLO WORD'})