Https://www.cnblogs.com/gyh04541/p/7910004.html of forwarding
Ways to query the API:
Table. Objects.all ()---[Obj1,obj2,....]
Table. Objects.all (). First ()
Table. Objects.filter (id=2)---[Obj1,], get a collection object, only one in the collection, followed by first () or "0" to take a specific object
Table. Objects.get (id=2)---obj, get a separate object, OK to find, can be used, if found multiple or not, all error.
Queryset.first (), like the Get () method, gets an object
Queryset.last (), like the Get () method, gets an object
----Update and Save method differences
Book.objects.filter (id=5). Update (price=1000) #直接更新update is a method for Queryset collection objects, recommended
Save method
Book = Book.objects.get (id=5)
book.price=400
Book.save ()
------The value method,
VALUES (*field), to get an iterative dictionary sequence, is no longer an object, but the value of the object, #得到QuerySet集合是所有的记录, which is a dictionary, key is a field, value is
defQuery_value (Request): B1= Book.objects.values ('title')#Title Value Field #Print (B1) #得到QuerySet集合是所有的记录, Inside is a dictionary, key is a field, value is #< queryset[{' title ': ' Linux '}, {' title ': ' Xiangtalan '}, {' title ': ' The person chasing the kite '}, {' title ': ' Rich Dad '}] >B2= Book.objects.values ('title',' Price')#multiple fields can be added Print(B2)#< queryset[{' title ': ' Linux ', ' Price ': Decimal (' 30.00 ')}, #{' title ': ' Xiangtalan ', ' Price ': Decimal (' 45.00 ')}, #{' title ': ' The person chasing the kite ', ' Price ': Decimal (' 39.90 ')}, #{' title ': ' Rich Dad ', ' Price ': Decimal (' 23.00 ')}] >B3= Book.objects.filter (id__gt=4). VALUES ('title')#Query ID greater than 4, title, get a collection of objects, display the title #<queryset [{' title ': ' Rich Dad '}]> Print(b3)returnHttpResponse ('Query method for the value method')
---
Value_list () Gets the data in a tuple format, with only the value of the field,
# ----ValueList method Query , get a tuple format data, only the value of the field, b4 = Book.objects.filter (id__gt=3). Values_list (' title ' Print (B4 )#<queryset [(' Man Chasing a Kite ',), (' Rich Dad ',)]>
Exclude () method,
B5 = Book.objects.exclude (id__gt=3)#exclude excluded, query ID greater than 4 for books, <queryset [<book:linux> <book: Xiangtalan >]> = Book.objects.filter (id__lt=4)# Query ID less than 4 book <queryset [ <book:linux>, <book: Xiangtalan >]> print(b5) print(B6) #B5 and B6 get the same results,
----
Additional Query methods
#<6>order_by (*field): Sorting Query Results#<7>reverse (): Reverse-sort the results of the query,---need to sort order_by (*field) before reversing#<8>distinct (): Remove duplicate records from the returned results#<9>values_list (*field): It is very similar to the values (), it returns a tuple sequence, and values returns a dictionary sequence#<10>count (): Returns the number of objects in the database that match the query (QuerySet). #<11>first (): Returns the first record#<12>last (): Returns the last record#<13>exists (): Returns True if Queryset contains data, otherwise false---only to determine if there is a record
Universal Double underline:
#---------------a great double underline (__) Single-table condition query----------------
# models. Tb1.objects.filter (id__lt=10, id__gt=1) # Get a value with an ID greater than 1 and less than 10 #
# models. Tb1.objects.filter (Id__in=[11, 22, 33]) # Get data with ID equal to 11, 22, 33
# models. Tb1.objects.exclude (id__in=[11, [+]) # No in # Exclude does not contain the specified data
# models. Tb1.objects.filter (name__contains= "ven") #包含的内容
# models. Tb1.objects.filter (name__icontains= "Ven") # Icontains case insensitive
# # # models. Tb1.objects.filter (Id__range=[1, 2]) # range Bettwen and #
# Startswith,istartswith, EndsWith, Iendswith,
Match the route and view functions in the URL file add
# MySQL copy is not available, there are configuration information, # is to need to modify the configuration from Import = [ url (r'^admin/', admin.site.urls), URL (r ' ^add/$ ' , Views.add),]
There are 2 ways to add a record
There are 2 types of Create methods, the Save method
Create Method 1: Add data to a one-to-many relational table, write dead, directly corresponding to the database field is added, is a set of group key value pairs
Add a record to the publish table first, manually add, click--minus the right DB can be saved,
Note: The Publish table is on the Book table, because when the table is generated, the Book table has publish_id fields, so we will find the Publish table first, and then add the corresponding ID number in the book, or error
Create a table in the model,
Book and publish is a one-to-many relationship, a publishing house can publish a variety of books, foreign keys will be built in a number of tables,
From django.db import Models
# Create your models here.
Class Publish (models. Model):
Name = models. Charfield (MAX_LENGTH=32)
Addr = models. Charfield (MAX_LENGTH=32)
Class book (Models. Model):
title = models. Charfield (MAX_LENGTH=32)
Price = models. Decimalfield (max_digits=5, decimal_places=2)
#书籍与出版社是一对多, the book is more, the publishing house is a, foreign key (sub-table) built in a number of tables,
#publish establishes a one-to-many relationship as a foreign key to the Book table, which is bound to the book's primary key ID by default
Publish = models. ForeignKey (Publish,)
#一对多的增删改查,
#做增加
#先给一 table to add data, in order to increase the number of tables in the corresponding data, or publish_id no value,
fromDjango.dbImportModels#Create your models here.classPublish (models. Model): Name= Models. Charfield (max_length=32) Addr= Models. Charfield (max_length=32)classBook (models. Model): Title= Models. Charfield (max_length=32) Price= Models. Decimalfield (max_digits=5, decimal_places=2) #Books and publishers are one-to-many, the book is more, the publishing house is a, foreign key (sub-table) built in a number of tables, #Publish establishes a one-to-many relationship with the Book table as a foreign key, which is bound to the book's primary key ID by defaultPublish =models. ForeignKey (Publish,)#a pair of more additions and deletions,#do increase#add data to a table first to increase the data in the corresponding number of tables, or publish_id no value,
In the Views file
First, import the table Book table from the model already created key, add data to the Book table,
Book.objects.cteate (), creating a table with the Create method,
The database field corresponds to the value to be added, and then the project is run
fromDjango.shortcutsImportRender,httpresponse#Create your views here. fromGu_orm.modelsImport* -----Import all the tables from the models table,defAdd (Request):#add a book recordBook.objects.create (Title='City of Thousand cities', Price= 11.90, publish_id= 1#subject to the fields in the database, ) returnHttpResponse ('OK')
At this point you can see a record in the Database Book table and a record of publish
=====
Gets the concrete value of the object, a single Object field property
# get a record from the database, Book_obj = Book.objects.get (id=1) print(book_obj.title) print(book_ Obj.price)
Run the project, get the results,,,
City of Thousand cities 11.90
Now print a field of a foreign key in the Book table publish
Print (book_obj.publish) ------Publish Object , which is a record in the Publish table, corresponds to a record in the book, is an object because it is a one-to-many relationship
To display the specific value of the foreign key, add __str__ (self) to the Publish table: the specific value is displayed, not the object
As follows
class Publish (models. Model): = models. Charfield (max_length=32) = models. Charfield (max_length=32) # with the __str__ () method, you can see the object specific value, without it, the print object, is an object, # When you use a field in a publish table, # You can see the object's specific values, not an object you can't read, def __str__ (self): return Self.name
The foreign key of the Book table is now printed,
# Print foreign key field publish Print (book_obj.publish) --- Beijing publishing House #Publish object is the one that corresponds to arecord in the Publsih table, which is an object, # Do not see the specific value, want to see the specific value of the object, using the __str__ () method, so in the models # can be used __str__ (), you can see the concrete value of the foreign key, but no longer an object,
---so in each table, you can use the __str__ (self) method to display the object's specific values
If you want to display more than one value, use the + sign, and remember to open the distance
def __str__ (self):
return self.name + "" +self.addr
Create Method 2 : Add data to a one-to-many relational table
Create a Publish object first
#方法2, first find a Publisher object publish_obj = Publish.objects.get (id=2)
Then use the Create method to give the Publish_obj object to the Publish table
#创建book对象, Book.objects.create ( title = ' Xiangtalan ', price = 23.50, publish = Publish_obj, )
Run the program, re-access the View function Add,url the address bar to re-access add, the database on the newly added records
Add Record Method 2,
=====save method
#save method, save the object with an instance
# a couple more,
p = Publish (name= ' Publishing house ', addr= ' changping ')
P.save () #把对象保存到数据库
#与PUblish表添加一个对象, both a record
Book = Book (title = ' Kid Chasing kites ', Price = ' 15.00 ', publish = P)
#与PUblish的publish_id绑定一个存在的记录, both objects
Book = Book (title = ' Kid Chasing kites ', Price = ' 15.00 ', publish_id = 3)
Book.save () #保存到数据库
Django one-to-many add record create and save method, update update and save () method differences, Query API method