.Django ten single-table operation (ORM)

A single-table operation .ORM --------

1. Create a table orm

python manage.py makemigrations # generate create table script    
python manage.py # generate database table
2 , you must install pymysql pip install pymysql

3 , under the project name __init__ found documents written in it:
 Import pymysql
pymysql.install_as_MySQLdb()
# Models.py 

form django.db Import Models
 class Book (models.Model):  # table book, django will automatically use the project name + we define the table name 
  # if there is no custom primary key, django will automatically add a primary key field self-energizing id name 
  name = models.CharField (= 20 is MAX_LENGTH)  # field name type name vachar (20 is) 
  price = models.IntegerField ()   # field name type price int 
  pub_date models.DateField = ()   # field name type pub_date date ( timestamp) 
   author = models.CharField (= 32 MAX_LENGTH, null = False) # default may be empty, can not be set to null = False empty 
  DEF  __str__ : (self)
    return the self.name  # display when printing is self instance object. name

 2. CRUD (single table operation) on the data table through the view function

# views.py

from django.shortcuts Import the render
 from app_name.models Import *  # introduced into the models.py 

DEF the Add (Request):  # increase view function data   # manner a   b = Book (name = 'python base', price = 99, author = ' Yuan ', pub_date =' 2017-12-12 ' )   b.save()   # Second way   Book.objects.create (name = 'python base',. Price = 99, author = 'Yuan', pub_date = '2017-12-12' )    # Book.object.create (DIC **) This written # when the value of the to be correspondence table sent by the client, the client can be used directly transmitted dictionary   return the HttpResponse ( ' added successfully ' )   
DEF Update (Request):  # view function to modify data   # manner a   b = Book.objects.get (author = 'yuan ') # Example get the object will get a Book, but when get to zero or more objects when being given   b.price = 109      b.save ()  # this embodiment will be reassigned each field, inefficient   # Second way   Book.objects.filter (author = 'yuan') . update (price = 109) # use QuerySet filter will get a set of objects (which is the book each object instance), because you can get multiple results, based on screening; all for the price of the book was changed to 109 yuan    # would only want to modify the field assignment, efficient return the HttpResponse ( ' successfully modified ' )
DEF the Delete (Request):  # view function to delete data   Book.objects.filter (author = 'Yuan') the Delete (). return HttpResponse ( ' deleted successfully ' )

 

 3. query (single table operation) on the data table through the view function

   filter () filter 
[: 3] taken
first () first
last () the last
values () Returns a collection of object dictionary
values_kist () Returns a collection of tuples objects
the exclude () does not contain the
DISTINCT () remove weight
count () Get the total recording number

order_by () to sort
get () Gets
def select(request):
  book_list = Book.objects.filter (ID = 2)  # conditional query returns a collection of objects QuerySet
  book_list Book.objects.all = ()  # query returns a result of all QuerySet collection object
  book_list = Book.objects.all () [ : 3]  # slicing operation from the former three; [:: 2] 2 via the steps of taking; [:: --1] backwards take
  book_list Book.objects.first = ()  # take the first return an instance of the object
  = Book.objects.last book_list ()  # take returns a last instance object
  book_list = Book.objects.get (ID = 2)  # conditional query returns a Book when the object instance is not being given only a record taken
book_list = Book .objects.filter (ID = 2) .values ( ' name ' , ' . price ' ) #select name, price form book where id = 2; QuertSet this case returns a collection of objects, but this is a collection of a dictionary object
book_list = Book.objects.filter (ID = 2) .values_list ( ' name ' , ' . price ' ) # SELECT name, form Book. price WHERE ID = 2; QuertSet this case returns a collection of objects, but this is one set of tuple
book_list = Book.objects.exclude (author = ' yuan ' )  # returns comprising author = 'yuan' of QuerySet that
book_list Book.objects.all = (). values ( ' name ' ) .distinct ()  # the name deduplication, meaningless without specific fields, because the table has a primary key, not recorded repeat
book_list = Book.objects.all (). cOUNT ()  # get the number of records returned a number
book_list = Book.objects.order_by('name')  # 按name进行排序
  return render(request,'index.html',{'book_list':book_list})

 4. query (double underlined universal single-table operation) on the data table through the view function

__gt comprising greater than __lt __in comprising less than __icontains not_in __range not included within the scope of   


Book.objects.filter (price__gt = 50)  #query the price is greater than 50
Book.objects.filter (name__icontains ='P')  #query which contains the name of p insensitive; name__contains = 'p' case-sensitive
models.Tb1.objects.filter (id__lt = 10, id__gt = 1) #acquires id value greater than 1 and less than 10 models.Tb1. objects.filter (id__in= [. 11, 22 is, 33 is]) #Gets the id data equal 11,22,33
models.Tb1.objects.exclude (id__in = [. 11, 22 is, 33 is]) #Not in 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 and bettwen
startsWith, istartswith, endsWith, iendswith, # starts with, to what end the band i represents not case sensitive Book.objects.filter (pub_date__year = 2016)  # queries all pub_date 2016 record
__exact         exactly equal like ' AAA ' 
__iexact        exactly equal to ignore case iLike ' AAA ' 
__contains      comprises like ' %% AAA ' 
__icontains     comprising ignoring case iLike ' %% AAA ' , but for sqlite, the effect equivalent to icontains contains .
__gt       greater than
 __gte      greater than or equal
 __lt       less than
 __lte      less
 __in       present within a range list
 __startswith     beginning ...
 __istartswith    beginning ... ignore case
 __endswith       to ... end
 __iendswith     Ending ..., ignore case
 __range       within ... range
 __year        year date field
 __month       month date fields
 __day         Day Date field
 __isnull = True / False
 __isnull = True and __exact = None of the difference

 5. Get sql statement corresponding to native orm

  author_obj=models.Author.objects.filter(id=2)

  print(author_obj.query)
Plus settings.py logging in the configuration file, the server can enter a corresponding sql statement orm

Copy the code
# The following code settings.py end of the file is added 

the LOGGING = {
     ' Version ' :. 1 ,
     ' disable_existing_loggers ' : False,
     ' handlers ' : {
         ' Console ' : {
             ' Level ' : ' the DEBUG ' ,
             ' class ' : ' the logging .StreamHandler ' ,
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

 

Guess you like

Origin www.cnblogs.com/lovershowtime/p/11355567.html