05- database basic operation

The basic database operations

  • In Flask-SQLAlchemy, insert, modify, delete, by the session management database.

    • Session expressed db.session. Before preparing the data written to the database, add data to the first session and then call commit () method to submit the session.
  • In Flask-SQLAlchemy, the query operation is an operation by a data query object.

  • The most basic query returns all the data in the table, can be performed more accurately through the filter database query.

Class definition model (foreign key) in view of the function

from Flask Import the Flask
 from flask_sqlalchemy Import SQLAlchemy 

App = the Flask ( the __name__ )
 # Set database connected the URL 
the app.config [ " SQLALCHEMY_DATABASE_URI " ] = ' MySQL: // the root: [email protected]: 3306 / flasksql ' 
the app.config [ " SQLALCHEMY_TRACK_MODIFICATIONS " ] = True
 # displays the original SQL query when 
the app.config [ " SQLALCHEMY_ECHO " ] = True 

db = SQLAlchemy (App)
 classRole (db.Model):
     # Definition Table name 
    __tablename__ = " Roles " 
    # defined column object 
    ID = db.Column (db.Integer, primary_key = True) 
    name = db.Column (db.String (64), UNIQUE = True )
     # add another model of relations "backreferences " method as the second parameter backref class User affirm the new property
    = db.relationship US ( " the User " , backref = ' Role ' ) 

    # the repr () method to display a readable string 
    DEF  __repr__ (Self):
         return  " Role:% S " % the self.name
 class the User (db.Model ):
     __tablename__ = " the Users " 
    the above mentioned id = db.Column (db.Integer, primary_key = True)
     # index If this column to create the index is True, to improve the efficiency of the query 
    name = db.Column (db.String (64) , unique True =, index = True) 
    In Email = db.Column (db.String (64), UNIQUE =  True)
    password= db.Column(db.String(64))
    #建立外键
    role_id = db.Column(db.Integer,db.ForeignKey("roles.id"))
    def __repr__(self):
        return "User:%s"%self.name
    
if __name__ == '__main__':
    app.run(debug=True)

Many

class Role (db.Model): 
    ... 
    # key code to create the reverse effect of many, the first parameter corresponding to the class name, the second parameter is a User class declaration new property 
    US db.relationship = ( ' User ' , backref = ' Role ' , lazy = ' Dynamic ' ) 
    ... # the third parameter lazy determines when SQLAlchemy to load data from a database

 class the User (db.Model): 
    ... 
    role_id = db.Column (db. Integer, db.ForeignKey ( ' roles.id ' ))
  • Realtionship which describes the relationship between the User and Role. In this context, the first parameter corresponding reference class "User"
  • The second parameter is a User class backref new properties stated method
  • The third parameter determines when SQLALchemy lazy load data from the database
    • If set to sub-query ( subquery ), it will be finished loading Role object, you will immediately load the associated objects, which would allow to reduce the total number of queries, but if the number of entries returned many, will be rather slow
      • Set subquery , then, Role . The Users return a list of all the data
    • Further, the embodiment may be provided as a dynamic ( Dynamic ), then this object is associated loads when in use, and filtered before returning, if the number of objects returned many, or in the future becomes a lot, it is preferable to use this way
      • Is set to dynamic , then, Role . The Users return a query object, and really did not do a query, the query object can be used to do other logic, such as: first sorted and then returns the result

Many to many

# Built outside a table, the relationship, the first parameter is declared registrations (Register)
# second argument, which is the first column of the table id statement, the second parameter description id type, the third parameter is explained outside built, foreign key parameter is the point properties
# The third parameter, which is the first column of the table id statement, the second parameter description id type, the third parameter instructions are built outside, foreign key parameter is the point properties
#注册表格
registrations = db.Table('registrations', db.Column('student_id', db.Integer, db.ForeignKey('students.id')), db.Column('course_id', db.Integer, db.ForeignKey('courses.id')) ) class Course(db.Model): ... class Student(db.Model): ... courses = db.relationship('Course',secondary=registrations, backref='students', lazy='dynamic')

Common SQLAlchemy query filters

filter Explanation
filter() Add the filter to the original query, the query returns a new
filter_by() Add the equivalent filter to the original query, the query returns a new
limit The value specified defines the original query results returned
offset() Offset from the original query results returned by the query returns a new
order_by() Sort the original query results according to specified conditions, to return a new query
group_by() The original query results are grouped according to specified criteria, returns a new query

Common SQLAlchemy query executor

method Explanation
all() Return query results as a list of all
first() Returns the first result of a query, if not found, return None
first_or_404() Returns the first result of a query, if not found, returns 404
get() Returns the row corresponding to the primary key, if not present, returns None
get_or_404() Returns the row corresponding to the primary key, if not present, returns 404
count() Returns the number of query results
paginate() Returns a Paginate object that contains the results within the specified range

Create a table

db.create_all()

Delete table

db.drop_all()

Insert a data

# To insert a field 
RO1 = Role (name = " ADMIN " )
 # add data 
db.session.add (RO1)
 # must be submitted to 
db.session.commit () 


# continue to insert a data 
RO2 = Role (name = " the User " ) 
db.session.add (RO2) 
db.session.commit ()

Insert multiple pieces of data:

us1 = User(name='wang',email='[email protected]',password='123456',role_id=ro1.id)
us2 = User(name='zhang',email='[email protected]',password='201512',role_id=ro2.id)
us3 = User(name='chen',email='[email protected]',password='987654',role_id=ro2.id)
us4 = User(name='zhou',email='[email protected]',password='456789',role_id=ro1.id)
us5 = User(name='tang',email='[email protected]',password='158104',role_id=ro2.id)
us6 = User(name='wu',email='[email protected]',password='5623514',role_id=ro2.id)
us7 = User(name='qian',email='[email protected]',password='1543567',role_id=ro1.id)
us8 = User(name='liu',email='[email protected]',password='867322',role_id=ro1.id)
us9 = User(name='li',email='[email protected]',password='4526342',role_id=ro2.id)
us10 = User(name='sun',email=' [email protected] ' , password = ' 235 523 ' , role_id = ro2.id)
 # plurality of data sequentially on the add_all () inside
db.session.add_all ([us1, us2, us3 , us4, us5, us6 , US7, US8, the Us9, US10]) db.session.commit ()

Query: filter_by precise inquiry

Returns the name of equal to everybody wang

User.query.filter_by(name="wang").all()

first () returns the first object query to

User.query.first()

all () returns the query to all objects

User.query.all()

All data filter fuzzy query, returns the name of the character to the end of the g

User.query.filter(User.name.endswith("g")).all()

get (): primary key parameter, if no primary key exists not return content

User.query.get()

Logical NOT, returns the name does not mean all the data wang

User.query.filter(User.name !="wang").all()

not_ equivalent negated

from sqlalchemy import not_

User.query.filter(not_(User.name=="wang")).all()

And logic, and need to import, and return () satisfies the conditions of all the data

from sqlalchemy import and_

User.query.filter(and_(User.name != "wang",User.email.endswith("163.com"))).all()

Or logic, need to import or_

from sqlalchemy import or_

User.query.filter(or_(User.name !="wang",User.email.endswith("163.com")))

After the query data is deleted

user = User.query.first()

db.session.delete(user)
db.session.commit()
User.query.all()

update data

= the User User.query.first () 
user.name = " zhang " 
db.session.commit () 
# after the update query 
User.query.first ()

Related inquiries

Relationship role and user-many relationship, a character can have multiple users, a user can belong to only one role.

Query role of all users:

# Query table id roles for a role 1 
RO1 = Role.query.get (1 )
 # All user queries the role of direct point-to-many queries return all property in point 
ro1.us.all ()

Queries the user belongs to role

# Queries users for the user id table 3 
US1 = User.query.get (3 ) 

# inquire what role the user belongs to many-to-point model to query the class lowercase 
us1.role

 

 

 

 

Guess you like

Origin www.cnblogs.com/lishuntao/p/11695034.html