65. django model layer-Basics of adding, querying, and modifying a single table, djangomodel
In the previous article, we introduced how to create, view, and delete tables in a simple book. Today we will introduce how to add and modify tables, because adding, modifying, and deleting tables are just as simple, this article will introduce a little more about single-table queries. We all know that queries in databases are the most important part. After all, no matter whether it is modification or deletion, many other operations are based on data query.
Today, all the examples use the continuation of the previous database, and the book table is also the continuation of the previous article, and then yesterday's table creation, deletion and other functions to expand other functions, so if you have any questions, you can first read the article:
Http://www.cnblogs.com/liluning/p/7729607.html
1. Add
1. Add Table records
1) method 1
Book_obj = models. Book (nid = nid, title = title, author = author, publishDate = publishDate, price = price) book_obj.save () # Save data to the database
2) method 2
# Book_obj can return the value book_obj = models. Book. objects. create (title = title, author = author, publishDate = publishDate, price = price)
2. template
1) Add button on the home page
<A href = "/addBook/"> <button class = "btn-primary"> Add a book </button> </a>
2) Add a Page Submission Form
<Form action = "/add/" method = "post" >{% csrf_token %} <tr> <td> <input type = "text" name = "title"> </td> <input type = "text" name = "author"> </td> <input type = "date" name = "publishDate"> </td> <input type = "text" name = "price"> </td> <button class = "btn-info"> submit </ button> </td> </tr> </form>
{% Csrf_token %} previously said that the security mechanism is used in post requests.
3. url Distribution
url(r'^add/', views.addBook),
4. View function views
Def addBook (request): if request. method = "POST": nid = request. POST. get ("nid") title = request. POST. get ("title") author = request. POST. get ("author") publishDate = request. POST. get ("publishDate") price = request. POST. get ("price") # book_obj = models. book (title = title, author = author, publishDate = publishDate, price = price) # book_obj.save () # Save the data to the database book_obj = models. book. objects. create (title = title, author = author, publishDate = publishDate, price = price) return redirect ("/index/") return render (request, "add.html ")
First, get the data submitted by the form and add it to the table.
Recommended method 2 for adding a table
Ii. Single Table query
1. query related APIs
Distinguish object from querySet
Yesterday, we introduced: <1> all (): <2> filter (): <3> get (): returns the object that matches the given filter condition, there is only one returned result. If more than one or none of the objects meet the filtering conditions, an error is thrown. (Use with caution) <4> exclude (): it contains an object that does not match the given filter condition <5> values (): returns a ValueQuerySet -- a special QuerySet, what we get after running is not a series of model instantiation objects, but an iterative dictionary sequence <6> values_list (): It is very similar to values, it returns a tuple sequence, and values returns a dictionary sequence <7> order_by (): sorts the query results <8> reverse (): reverse sorting of query results <9> distinct (): removes duplicate records from the returned results <10> count (): returns the number of objects that match the query (QuerySet) in the database. <11> first (): returns the first record <12> last (): returns the last record <13> exists (): returns True if QuerySet contains data; otherwise, returns False.
View Code
Example: <2>filter(nid=nid,title=title) ',' Can act as the database and. The two condition relations are also, and the condition relations 'or' cannot be implemented in parentheses. The subsequent articles will be introduced one by one.
2. Double-underline Single Table query
1 models. tb1.objects. filter (id _ lt = 10, id _ gt = 1) # obtain the value of id greater than 1 and less than 10 #__ lte ,__ gte is less than or equal to 2 models. tb1.objects. filter (id _ in = [11, 22, 33]) # obtain data 3 models with IDs equal to 11, 22, and 33. tb1.objects. exclude (id _ in = [11, 22, 33]) # not in4 models. tb1.objects. filter (name _ contains = "ven") # fuzzy query 5 models. tb1.objects. filter (name _ icontains = "ven") # icontains case insensitive 6 models. tb1.objects. filter (id _ range = [1, 2]) # range: bettwen and7 startswith, istartswith, endswith, iendswith
3. You can use logging to view translated SQL statements.
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, }}
Paste the above Code into the setting configuration file. When your operation is related to the database, the statements we write will be translated into SQL statements and printed on the server.
4. The following code is only an example of a test SQL statement and a single table query.
1) url Distribution
url(r'^query/', views.query),
2) view function views
Def query (request): # query method API: #1 all: models. table name. objects. all () # book_all = models. book. objects. all () # The result is the querySet set [model object,...] # print (book_all) # <QuerySet [<Book: Book object>, <Book: Book object>, <Book: Book object>]> #2 filter: models. table name. objects. filter () # The result is the querySet set [model object,...] # ret1 = models. book. objects. filter (author = "yuan") # <QuerySet [<Book: kite chaser>, <Book: asd>]> # ret2 = models. book. objects. filter (nid = 1) # <QuerySet [<Book: yuan>]> # ret2 = models. book. objects. filter (author = "yuan", price = 123) # <QuerySet [<Book: yuan>]> # print (ret2) #3 get models. table name. objects. get () # model object # ret3 = models. book. objects. get (author = "yuan") # print (ret3.price) # exclude: exclusion condition # ret4 = models. book. objects. exclude (author = "yuan") # print (ret4) # values method # ret = models. book. objects. filter (author = "yuan "). values ("title", "price") # print (ret) # <QuerySet [{'title': 'kite chaser ', 'price': Decimal ('99. 00')}, {'title': 'asd ', 'price': Decimal ('2017. 00')}]> # ret = models. book. objects. filter (author = "yuan "). values_list ("title", "price") # print (ret) # <QuerySet [('kite chaser ', Decimal ('99. 00'), ('asd ', Decimal ('100. 123. 00')]> # ret = models. book. objects. filter (author = "yuan "). values ("author "). distinct () # print (ret) # count method # ret = models. book. objects. filter (author = "yuan "). count () # print (ret) # first method ret = models. book. objects. all (). first () print (ret) # exists method # if models. book. objects. all (). exists (): # print ("exists") # else: # print ("nothing") # ret = models. book. objects. filter (price _ gt = 100) # ret = models. book. objects. filter (price _ gte = 99) # greater than or equal to # ret = models. book. objects. filter (publishDate _ year = 2017, publishDate _ month = 10) # ret = models. book. objects. filter (author _ startswith = "") # print (ret) return HttpResponse ("OK ")
Take the first method as an Example
From this we can see that although we did not write SQL statements when operating the database, django translates the statements we write into SQL statements.
3. Modify
1. Modify Table records
There are two ways to modify a table record and add a table record. We can view the specific application of modifying a table record in view function views.
Nid = request. POST. get ("nid") title = request. POST. get ("title") author = request. POST. get ("author") publishDate = request. POST. get ("publishDate") price = request. POST. get ("price") # Modification Method 1: save (low efficiency) # book_obj = models. book. objects. filter (nid = id) [0] # example of modifying the title: # book_obj.title = "py2" # book_obj.save () # Method 2: (recommended) models. book. objects. filter (nid = nid ). update (title = title, author = author, publishDate = publishDate, price = price) return redirect ("/index /")
2. url Distribution
url(r'^edit/(\d+)', views.editBook),
3. template
1) homepage modification button
<A href = "/edit/{book_obj.nid}"> <button class = "btn-info"> edit </button> </a>
2) the data source is the same as the data added to the table. Different from the form submission in the template, the original data needs to be defaulted in the modified form.
<Form action = "/edit/{edit_obj.nid}" method = "post" >{% csrf_token %} <tr> <td >{{ forloop. counter }}< input type = "hidden" name = "nid" value = "{edit_obj.nid }}"> </td> <input type =" text "name = "title" value = "{edit_obj.title}"> </td> <input type = "text" name = "author" value = "{edit_obj.author}} "> </td> <input type =" date "name =" publishDate "value =" {edit_obj.publishDate | date: "Y-m-d" }}"> </td> <input type = "text" name = "price" value = "{edit_obj.price}"> </td> <a href = "/del/{edit_obj.nid}"> <input type = "button" class = "btn-danger" value =" delete "> </a> <button class =" btn-success "> Save </button> </td> </tr> </form>