Django &, Flask & pyrthon native sql statement Basic Operations

Django framework, Flask ORM framework and pyrthon native sql database operation statement

 

WHAT IS ORM?

ORM (Object Relational Mapping) object-relational mapping, i.e. to achieve the object-oriented way of thinking by the operation of the database.

Operation class model objects into sql statement

And mapping database table relations implemented model classes in the module: the developer only with the instance of the corresponding object within a model operation, the underlying function will be automatically converted to additions and changes to be implemented sql statement to the database search deleted

 

Advantages: 1 simple operation more understandable to write code simple, 2 compared to native sql statement can save a small amount of code that can save a lot of development time, in line with the current development of mainstream thinking with space for time shorten the development cycle and reduce development difficulty

Disadvantages: ORM mapping operation to establish a model for the inner class object to execute the command is still sql statement reflected this process there are a lot of performance overhead problem, simply now have lazy loading, caching mechanism that allows ORM performance overhead is greatly reduced, I believe the future will be lower to a negligible

 

Currently python mainstream framework Django, Flask and native sql statement in contrast actual programming

Native sql

PyMySQL module

Even python3 Solutions database module

Implementation process

An import module package 
2 to create the connection objects
3 acquires cursor object
4 prepared sql statement
5 execute sql statement 5.1 queries - to accept the results 5.2 CRUD statement - submitted perform or execute a rollback 6 Close cursor objects 7 close connection object

   


   

 

 

CURD operation of the database

 

Django

django.db module

Django framework built database mapping module

Implementation process

0 configuration database 
define a model class
instance created object model class 2
3-implemented method using an object in the database CURD

Module model class definitions django.db

Guide package models

All custom model classes inherit models.Model

Case:

the BookInfo class (models.Model): 
# django.db automatically mapped without specifying field id
# as CharField specified data type parameter is a string type field constraint
name = models.CharField (default = 0, verbose_name = ' title') # mapping database table column name attribute name
# IntegerField specify a data type parameter is a field constraint integer
count = models.IntegerField (default = 0, verbose_name = ' rEAD') # database table column name attribute name mapping class Meta -:       named db_table, = ' tb_books' # specified database table name mapping table       verbose_name = 'book' # name displayed in admin site       verbose_name_plural = plural name the verbose_name # display       DEF __str __ (Self):       "" "display information defining each data object" ""       return self.btitle





       



   

 

CURD operation of the database

create:

Case

 

# Native sql insert into tb_book values (0, " Sorrows of Young Werther", 1000) 
method
Book = BookInfo ( name = "Sorrows of Young Werther," COUNT = 1000)
Book. The Save ()
method two upgraded version
BookInfo. Objects . the Create ( name = "Midsummer Night's Dream", COUNT = 1000 )



update:

Case

# Native sql update tb_book set name = "Siege" where id = 1; 
Method a:
Book = BookInfo.objects.get (= ID. 1)
book.name = "Siege"
book.save ()
Method II upgrade:
#. objects.filter.update () will modify all rows generally filtered out by the filter condition ID
BookInfo.objects.filter (name = "human disqualification") .update (name = "Journey")

 

read:

Case

 # Access to all data lines, SELECT * FROM SQL equivalent of list_all = the BookInfo. Objects. All () # filter corresponds to the SQL WHERE, filter set condition results list_filter = the BookInfo. Objects. Filter ( COUNT = 1000) # obtaining a single object response1 = . the BookInfo . objects GET ( ID = . 1) # data ordering list_all = the BookInfo. objects. All (). ORDER_BY ( "COUNT") # restrict a SQL data corresponding to the lIMIT 2 0 in the OFFSET; list_limit = . the Test . Objects . All () ORDER_BY ( 'COUNT', desc) [ 0: 2]





 

 
 

 

delete:

Case

原生sql delete from tb_book where id=1
test1 = BookInfo.objects.get(id=1)
test1.delete()

 

This view ORM and native sql or less

Object-oriented inheritance powerful advantage in packaging capacity

After adding DRF frame CURD Django framework of the database will be encapsulated directly to the bottom, the developer only specified route, serializer, to model class

Complete CURD

 

Flask

SQLAlchemy module

Flask is a lightweight frame not carrying module ORM package generally used SQLAlchemy

Implementation process

0 configuration database 
define a model class
instance created object model class 2
3-implemented method using an object in the database CURD

Module model class definitions SQLAlchemy

db = SQLAlchemy (app) for all model classes inherit db.Model

Case:

the BookInfo class (db.Model): 
	# mapping database table 
	 __tablename__ = 'user_basic' 
     # mapped column parameters (Table class field name, data type, other constraints ..., the name displayed in the site admin) 
	 ID = db.Column ( ' user_id ', db.Integer, primary_key = True , doc =' books id ')

 

 

CURD operation of the database

SQLAlchemy operation instruction module closer PyMySQL

create:

Case

# Native sql insert into tb_book values (0, " Sorrows of Young Werther", 1000) 
method 
book = BookInfo (name = "Sorrows of Young Werther") 
db.session.add (Book) 
db.session.add_all ([user1 , user2, user3]) # batch increase 
db.session.commit ()

 

update

Case:

# Native sql update tb_book set name = "Siege" where id = 1; 
Method a: 
Book BookInfo.query.get = (. 1) 
book.name = "Siege" 
db.session.add (Book) 
db.session.commit ( ) 
method II upgrade version: 
# django.db Update is passed named parameters are passed SQLAlchemy update the dictionary 
BookInfo.query.filter_by (name = "human disqualification") .update ({(name: " Journey to the West"})) 
db .session.commit ()

 

read

Case:

Method One: 
# get all the rows of data, the equivalent of the FROM SQL * in the SELECT 
 list_all = BookInfo.query.all () 
 # inquire what is the use of a? 
 Book book.query.first = () 
 # according to the query ID, not primary key exists return None [django.db the additional fields may be checked will not get an error] 
 Book book.query.get = (. 1)    
method II: 
    list_all = db.session.query (the BookInfo) .all () 
    Book = db.session.query (the BookInfo) .first () 
    Book = db.session.query (the BookInfo) .get (. 1) 
 # filter_by filter and corresponds to the SQL WHERE, filter set condition results 
 list_filter = BookInfo.query.filter_by (COUNT = 1000) #filter_by 
 list_filter = BookInfo.query.filter (BookInfo.count == 1000)   
#filter global filter is to specify conditions for use python model comparison symbols 
# and fiest () while using similar unique data filtering django.db GET 
 # offset the starting offset is set worth 
 list_all = BookInfo.query.offset (2) .all ()
Limiting access to data # 
 list_all BookInfo.query.limit = (. 3) .all () 
  # data sorting 
list_all = BookInfo.query.order_by (BookInfo.id.all () 
 list_all = BookInfo.query.order_by (BookInfo.id.desc ( )). all ()
 

 

 

 

 

Guess you like

Origin www.cnblogs.com/renoyuan/p/11284696.html