Instances operated by the Django database (add, delete, modify, and query), and add or delete django
Create a table in the database
Class Business (models. Model): # automatically create the ID column caption = models. CharField (max_length = 32) code = models. CharField (max_length = 32)
1. Add
Method 1
Models. Business. objects. create (caption = 'marketing Department ', code = '123 ')
Method 2
Obj = models. UserInfo (caption = 'marketing Department ', code = '000000') obj. save ()
Method 3
Dic = {'caption ': 'marketing Department', 'code': '000000'} models. Business. objects. create (** dic)
2. Delete
models.Business.objects.filter(id=1).delete()
For the query method, see the query below
3. Change
Method 1
models.Business.objects.filter(id=1).update(code='hello')
Method 2
obj = models.Business.objects.get(id=1)obj.code = 'hello'obj.save()
For the query method, see the query below
4. Query
Get all
V1 = models. Business. objects. all () # QuerySet type, internal elements are all objects
Get specified
V2 = models. business. objects. all (). values ("id", "caption") # QuerSet type, internal elements are dictionaries v3 = models. business. objects. all (). values_list ('id', 'caption ') # The QuerySet type. The internal elements are all tuples v4 = models. business. objects. get (id = 1) # get a team image. If it does not exist, the system reports the v5 = models error. business. objects. filter (id = 1) # QuerySet type, the internal element is an object, id _ gt = 1 get all id> 1 data, id _ lt = 10, obtain data of all IDs <10 v6 = models. business. objects. filter (id = 1 ). first () # Return object or None
Application Instance
Business functions
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>
The above Django database operation instance (add, delete, modify, and query) is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for our customer base.