First, add table records
There are two ways for a single table
#two ways to add data #Way One: Instantiating an object is a table recordFrank_obj = models. Student (name ="Haidong", course="python", birth="2000-9-9", fenshu=80) Frank_obj.save ()#Way Two:Models. Student.objects.create (name ="Haiyan", course="python", birth="1995-5-9", fenshu=88)
Second, query table records
Querying related APIs
#Querying related APIs #1. All (): View allStudent_obj =models. Student.objects.all ()Print(student_obj)#The result of printing is the Queryset collection #2, filter (): Can be achieved and relations, but or relations need to use Q query implementation ... #No errors when you can't find them. Print(Models. Student.objects.filter (name="Frank"))#Look, the name is Frank's. Print(Models. Student.objects.filter (name="Frank", fenshu=80))#Look, the name is Frank and the score is 80. #3, get (): If not found will be error, if there are multiple values, will also error, can only take a value of the Print(Models. Student.objects.get (name="Frank"))#got the model object. Print(Models. Student.objects.get (nid=2))#got the model object. #4, exclude (): Exclusion conditions Print(Models. Student.objects.exclude (name="Haidong"))#View information except the name is Haidong #5, VALUES (): is a method of Queryset (bar object into the form of a dictionary,) Print(Models. Student.objects.filter (name="Haidong"). VALUES ("nid","Course"))#See the number and course named Haidong #Print Result: <queryset [{' Nid ': 2, ' course ': ' Python '}, {' Nid ': ', ' course ': ' Python '}]> #6, Values_list (): Is a method of Queryset (bar object into the form of tuples) Print(Models. Student.objects.filter (name="Haidong"). Values_list ("nid","Course")) #Print Results:< queryset[(2, ' Python '), (+, ' python ')] > #7. Order_by (): Sort Print(Models. Student.objects.all (). Order_by ("Fenshu")) #8, reverse (): Reverse Print(models. Student.objects.all (). Reverse ())#9, DISTINCT (): To remove weight (as long as the results are repeated) Print(Models. Student.objects.filter (course="python"). VALUES ("Fenshu"). Distinct ())#10. Count (): View a few records Print(Models. Student.objects.filter (name="Haidong"). Count ())#11. First () #12. Last () returnRender (Request,"test.html",{"Student_obj": Student_obj}) #13, Esits: Check if there is no record, if there is return True, no return false #no need to judge all the data, #if models. Book.objects.all (). Exists ():
Double Underline single Table query
Models. Tb1.objects.filter (id__lt=10, Id__gt=1)#get a value that has an ID greater than 1 and less than 10models. Tb1.objects.filter (id__in=[11, 22, 33])#get data with ID equal to 11, 22, 33Models. Tb1.objects.exclude (Id__in=[11, 22, 33])# not inmodels. Tb1.objects.filter (Name__contains="Ven") #包括ven的models. Tb1.objects.filter (Name__icontains="Ven")#icontains case insensitivemodels. Tb1.objects.filter (Id__range=[1, 2])#Range Bettwen andStartswith,istartswith, EndsWith, Iendswith
objects can call their own properties, with a single point can also be double-underlined ... models. Book.objects.filter (price__gt=100) is a book with a price greater than 100 models. Book.objects.filter (Author__startwith" Zhang ") View the author's name is the beginning of the Primary key greater than 5 and less than 2 price__gte=99 is greater than or equal to =2017,publishdate__month = ten view October 2017 data
Cond.........
Third, modify the table record
Attention:
<1> the second way to modify cannot use get is because update is a method of the Queryset object, get returns a model object, it does not have an Update method, and filter returns a Queryset object ( The conditions within the filter may have multiple conditions, such as Name= ' Alvin ', which may have two rows of Name= ' Alvin '.
<2> in the Insert and Update Data section, we refer to the Save () method of the model, which updates all the columns in a row. In some cases, we just need to update a few columns in the row.
In addition, the update () method is valid for any result set (QuerySet), which means that you can update multiple records at the same time the update () method returns an integer value that represents the number of record bars affected.
Note that the query property is not available because the update returns a shape, and for each object you create, you want to display the corresponding raw SQL in the settings plus the logging section
Iv. deleting table records
The deletion method is delete (). It runs immediately when the object is deleted without returning any values. Example: E.delete ()
def delstudent (request,id): # Delete Data Models. Student.objects.filter (nid=id). Delete () return Redirect ("/test/ ")
You can also delete multiple objects at once. Each QuerySet has a delete () method that deletes all the objects in QuerySet at once.
For example, the following code removes pub_date as the Entry object for 2005:
Entry.objects.filter (pub_date__year=2005). Delete ()
Keep this in mind: regardless of the circumstances, the delete () method in QuerySet uses only one SQL statement to delete all objects at once, rather than deleting each object individually. If you want to use the Delete () method that is customized in model, you call the Delete method of each object yourself. (for example, traversing QuerySet, calling the Delete () method on each object) instead of using the Delete () method in QuerySet.
When Django deletes an object, it mimics the behavior of the SQL constraint on DELETE CASCADE, in other words, deleting an object also deletes the foreign key object associated with it. For example:
b = Blog.objects.get (pk=1)# This would delete the Blog and all of its Entry objects. B.delete ()
Note that the delete () method is a method on QuerySet, but does not apply to the Manager itself. This is a protection mechanism to avoid accidentally invoking the Entry.objects.delete () method, which causes all records to be mistakenly deleted. If you confirm that you want to delete all the objects, then you must explicitly call:
Entry.objects.all (). Delete ()
V. The syntax involved in editing the contents of a table
syntax analysis involved in editing operations:1, click Edit, let jump to another page, get the line I clicked two ways to take ID value one: Using data transmission parameters (as data parameters passed)<a href="/edit/?book_id = {{Book_obj.nid}}"></a>#equivalent to sending a key-value pairThere is no need to write a matching path in the URL, id= Request. Get.get ("book_id")#Take valuemethod Two: Use the path to the parameter, you have to add in the URL (\d+), you have to pass a parameter to the function, and the nameless group takes the value from the argument.<a href="/{{book_obj.nid}}"></a> 2, get the ID, and then do the filter ID= Request. Get.get ("book_id") Book_obj= Models. Book.objects.filter (Nid=id)#got a list object.Note:1take [0] to get the object, and then the object. The property can be taken to the value .2. With get, you have to take out the data must be only one time, if there are multiple use get will error,, but with get do not add [0] book_obj= Models. Book.objects.filter (nid=ID) [0]3, How to let the input box display the text content when click Edit value="{{Book_obj.title}}"4, re-submit the data after the submission of the time to go to action ...../edit/} hides an input,<input type="Hidden"Name ="book_id"Value="{{Book_obj.nid}}">when judging the post: Modify the Data mode one: Save (this way efficiency is very low, not recommended to use, understand on the line) modified The premise is to take (get the ID value to edit) ID= Request. Post.get ("book_id") Bk_obj= Models. Book.objects.filter (nid=ID) [0] Bk_obj.title="hhhhhh" #It's written dead, can't all be written like this.Bk_obj.save () as long as the object is used in this way. Save mode Two: Update title= Request. Post.get ("title") models. Book.objects.filter (Nid=id). Update (title=title,......) Jump to index if it is a POST request, how to find the ID, one, if it is a data transfer parameter: (that is, the GET request) can be through a hidden I Nput box, give this box a Name property, the Value property. Through request. Post.get ("Key"), you can get the value of the ID two, if the path is a parameter can be passed in the form of a parameter, when the regular expression write a (\d+), pass an ID to the function, which can be used to know the ID.
Django database table additions and deletions