Django数据库操作(增删改查)
创建数据库中的一个表
class Business(models.Model):
#自动创建ID列
caption = models.CharField(max_length=32)
code = models.CharField(max_length=32)
1.增加
方法一
1 models.Business.objects.create(caption='市场部',code='123')
方法二
1 obj = models.Business(caption='市场部',code='123')
2 obj.save()
方法三
1 dic = {'caption':'市场部','code':'123'}
2 models.Business.objects.create(**dic)
2.删除
models.Business.objects.filter(id=1).delete()
查询方法见下方查询
3.更改
方法一
1 models.Business.objects.filter(id=1).update(code='hello')
方法二
1 obj = models.Business.objects.get(id=1)
2 obj.code = 'hello'
3 obj.save()
查询方法见下方查询
4.查询
获取全部
v1 = models.Business.objects.all() #QuerySet类型,内部元素都是对象
获取指定
v2 = models.Business.objects.all().values("id","caption") #QuerSet类型,内部元素都是字典
v3 = models.Business.objects.all().values_list('id','caption') #QuerySet类型,内部元素都是元组
v4 = models.Business.objects.get(id=1) #获取一个队象,如果不存在就报错
v5 = models.Business.objects.filter(id=1) #QuerySet类型,内部元素是对象,id__gt=1获取所有id>1的数据,id__lt=10,获取所有id<10的数据
v6 = models.Business.objects.filter(id=1).first() #返回对象或者None
应用实例
![](https://static.oschina.net/uploads/img/201802/02125953_MMUs.gif)
![](https://static.oschina.net/uploads/img/201802/02125953_uaqM.gif)
1 def business(request):
2 v1 = models.Business.objects.all()
3 v2 = models.Business.objects.all().values("id","caption")
4 v3 = models.Business.objects.all().values_list('id','caption')
5 return render(request,"business.html",{"v1":v1,"v2":v2,"v3":v3})
![](https://static.oschina.net/uploads/img/201802/02125953_MMUs.gif)
![](https://static.oschina.net/uploads/img/201802/02125953_uaqM.gif)
1 url(r'^business$',views.business)
![](https://static.oschina.net/uploads/img/201802/02125953_MMUs.gif)
![](https://static.oschina.net/uploads/img/201802/02125953_uaqM.gif)
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6 </head>
7 <body>
8 <ul>
9 <h1>ALL</h1>
10 {% for row in v1 %}
11 <li>{{row.id}}-{{row.caption}}-{{row.code}}</li>
12 {% endfor %}
13 </ul>
14 <ul>
15 <h1>all.values</h1>
16 {% for row in v2 %}
17 <li>{{row.id}}-{{row.caption}}</li>
18 {% endfor %}
19 </ul>
20 <ul>
21 <h1>all.values_list</h1>
22 {% for row in v3 %}
23 <li>{{row.0}}-{{row.1}}</li>
24 {% endfor %}
25 </ul>
26 </body>
27 </html>