Home > Article > Backend Development > Examples of add, delete, modify and query operations in Django database
The following editor will bring you an example of Django database operation (add, delete, modify, check). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
Create a table in the database
class Business(models.Model): #自动创建ID列 caption = models.CharField(max_length=32) code = models.CharField(max_length=32)
1. Add
Method one
models.Business.objects.create(caption='市场部',code='123')
Method two
obj = models.UserInfo(caption='市场部',code='123') obj.save()
Method Three
dic = {'caption':'市场部','code':'123'} models.Business.objects.create(**dic)
2. Delete
models.Business.objects.filter(id=1).delete()
For the query method, see query below
##3. Change
Method one
models.Business.objects.filter(id=1).update(code='hello')
Method two
obj = models.Business.objects.get(id=1) obj.code = 'hello' obj.save()Query See the method below for query
4. Query
get all##
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 function
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)
<!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>
The above is the detailed content of Examples of add, delete, modify and query operations in Django database. For more information, please follow other related articles on the PHP Chinese website!