Django数据库操作的实例(增删改查)
创建数据库中的一个表
class Business(models.Model): #自动创建ID列 caption = models.CharField(max_length=32) code = models.CharField(max_length=32)
1.增加
方法一
models.Business.objects.create(caption='市场部',code='123')
方法二
obj = models.UserInfo(caption='市场部',code='123') obj.save()
方法三
dic = {'caption':'市场部','code':'123'} models.Business.objects.create(**dic)
2.删除
models.Business.objects.filter(id=1).delete()
查询方法见下方查询
3.更改
方法一
models.Business.objects.filter(id=1).update(code='hello')
方法二
obj = models.Business.objects.get(id=1) obj.code = 'hello' 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
应用实例
business函数
def business(request): v1 = models.Business.objects.all() v2 = models.Business.objects.all().values("id","caption") v3 = models.Business.objects.all().values_list('id','caption') return render(request,"business.html",{"v1":v1,"v2":v2,"v3":v3})
url(r'^business$',views.business)
business.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <ul> <h1>ALL</h1> {% for row in v1 %} <li>{{row.id}}-{{row.caption}}-{{row.code}}</li> {% endfor %} </ul> <ul> <h1>all.values</h1> {% for row in v2 %} <li>{{row.id}}-{{row.caption}}</li> {% endfor %} </ul> <ul> <h1>all.values_list</h1> {% for row in v3 %} <li>{{row.0}}-{{row.1}}</li> {% endfor %} </ul> </body> </html>