In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use the ORM system in the Django framework to add, delete and check database data". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly to study and learn "how to use the ORM system in the Django framework to add, delete and check database data"!
directory
1. Data addition, deletion, correction and query----------
Import the User model class into the view function, and add data using the following method:
2. Data addition, deletion, correction and query----------
The__str__() method defined at the time of defining the model class is then useful
User Model Class Import
3. Data addition, deletion, correction and query--------Delete data
4. Data addition, deletion, modification and query----------
1. Add, delete, and modify data---------Add data Import the User model class in the view function, and then add data using the following method: from django.http import HttpResponsefrom .models import User# Create your views here.def add_user(request): Method 1 taka = User(name='taka',age=18) taka.save() Method 2 xiaopo = User() xiaopo.name = 'xiaopo' xiaopo.age = 18 xiaopo.save() Method 3 aa = User.objects.get_or_create(name='xiaohong', age=18) #will look up before insertion, if there is no same data will be added; if there is, it will not. print(aa) #Returns a tuple, the first data is the instance successfully added; the second data is True or False. (True if successful; False otherwise) #Print results here: (, True) #Look up before insertion, add if there is no same data; if there is, don't. Because the same data is inserted above, no data is inserted here. User.objects.get_or_create(name='xiaohong',age=18) return HttpResponse("Insert data successfully! ")
Effect achieved:
(Note: Assign a route to this view to execute!)
2. Data addition, deletion, modification and query----------
Controls the format in which the query's data is displayed (that is, a simple representation of the model is displayed)
from django.db import models# Create your models here.class User(models.Model): id = models.AutoField(primary_key=True) #The primary key can be omitted, Django will add a primary key named id for us by default. If you write it, you can change the name of the primary key! name = models.CharField(max_length=50) # CharField--String age = models.IntegerField() # IntegerField--integer def __str__(self): """ Returns a string representation of the model We tell Django which attribute should be used by default to display information about this model Django calls the method__str__() to display a simple representation of the model """ return "name:%s, age:%s" %(self.name,self.age)
Enquiry:
User model class import from django.http import HttpResponsefrom .models import Userdef search_user(request): #Query all record objects rs1 = User.objects.all() print("This is all record objects: ", rs1) #Through observation, you can find that the output mode of the queried record object is the format of__str__in the model. #Also the query result rs1 is a queryset object, which is a list-like object. There are some common methods in the list, such as: slice [0:3], subscript rs1 [1]... However, if subscript values are reversed, they are not supported. #Query a record object rs2 = User.objects.get(name="xiaopo") #This method queries, if there is no/there are multiple items, an error will be reported! So generally through the ID value. print("This is a record object: ", rs2) #Query objects that meet the criteria rs3 = User.objects.filter(name='xiaoming') #Empty if not found; multiple items can be found print("This is an object that satisfies the condition:",rs3) return HttpResponse("Query data succeeded! ")
Note:
1.All() and filter() methods return QuerySet objects, which are empty if they are not queried (but they will not report errors anyway, which is awesome!).
2. A single object returned by get () method. If there are multiple objects that meet the conditions, get will report an error! And if you can't find it, you will report an error!
Effect achieved:
3. Extension--About QuerySet Two simple sentences:
QuerySet is an iterable object. QuerySet supports slicing, but does not support negative indexing. QuerySet can be forced into a list by using list.
3. Add, delete, and modify data-------delete data from django.http import HttpResponsefrom .models import Userdef delete_user(request): #Instance and QuerySet objects have delete methods! User.objects.get(id=1).delete() #get method gets a single object (an instance object), so delete a piece of data! User.objects.filter(age=18).delete() #Delete all data with age attribute value 18! User.objects.all().delete() Delete all data! s = User.objects.filter(age=18) s[1].delete() #Delete a specified entry in data with age value 18 return HttpResponse("Delete data successfully! ")4. Add, delete and modify data----------modify data from django.http import HttpResponsefrom .models import Userdef update_user(request): #The first method: find the data first, and then modify the attribute assignment (for instance modification) rs = User.objects.get(name="xiaoming") #Modify the name attribute value to xiaoming and the name attribute value to xiaowang (only modify the first item because the get method is used!) rs.name='xiaowang' rs.save() #The second method: use update method to modify directly (for collection modification, only for QuerySet object) User.objects.filter(name ='xiaowang ').update(name ='AAA') #Modify all name attribute values of xiaowang to AAA! User.objects.all().update(age=22) #Change the age attribute value of all data to 22! return HttpResponse("Modify data successfully! ") Thank you for reading, the above is" how to use the ORM system in the Django framework to add, delete and check database data "content, after learning this article, I believe that everyone on how to use the ORM system in the Django framework to add, delete and check database data This problem has a deeper understanding, the specific use of the situation still needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.