demand
Want to achieve dynamic queries, table names, field, field value is not fixed
. 1 obj = table .query.filter_by (field = value. 1) .first ()
2
. 3 obj. Field Value = 2
First, dynamic access to db_model name
1 class Role(db.Model):
2 __tablename__ = 'roles'
3 id = db.Column(db.Integer, primary_key=True)
4 name = db.Column(db.String(64))
5 email=db.Column(db.String(64))
6
7 def __repr__(self):
8 return '<Role %r>' % self.name
9
10 aa = globals()["Role"]
Validation results:
= aa.query.get obj (1 )
Print (obj)
# can get normal results
Dynamic query:
filter_by for simple query column names, do not support comparison operators
filters={'name':'lisa'}
obj = db_model.query.filter_by(**filters).first()
Validation results:
Print (obj) # Results <Role ' Lisa ' >
Complete code:
1 # Import dependency
2 from Flask Import the Flask, jsonify
. 3 from flask_sqlalchemy Import SQLAlchemy
. 4 # create a service
. 5 app = the Flask ( the __name__ )
. 6
. 7 # Configure app properties
. 8 # the URL of the database connection settings
. 9 the app.config [ ' SQLALCHEMY_DATABASE_URI ' ] = ' MySQL + mysqlconnector: // the root: [email protected]: 3306 / Test '
10
. 11 # is provided each time the database is automatically commit changes after the end of the request
12 is the app.config [ 'SQLALCHEMY_COMMIT_ON_TEARDOWN ' ] = True
13 is the app.config [ ' SQLALCHEMY_TRACK_MODIFICATIONS ' ] = True
14
15 # Show original SQL statement queries
16 the app.config [ ' SQLALCHEMY_ECHO ' ] = False
. 17
18 is # Response Display Chinese JSON,
. 19 the app.config [ ' JSON_AS_ASCII ' ] = False
20 is
21 is # generate a sqlalchemy target
22 is DB = SQLAlchemy (App)
23 is
24 #Create a model, in python by roles Role class mapping table body
25 class Role (db.Model):
26 is __tablename__ = ' roles '
27 ID = db.Column (db.Integer, primary_key = True)
28 name = db.Column ( db.String (64 ))
29 In Email = db.Column (db.String (64 ))
30
31 is DEF __repr__ (Self):
32 return ' <R & lt Role%> ' % the self.name
33 is
34 is # Get the name of model
35 db_model Globals = () [ " Role " ]
36 Print (db_model)
37 [
38 is # verification
39 obj db_model.query.get = (. 1 )
40 # using filter_by dynamic query inquiry
41 is Filters = { ' name ' : ' Lisa ' }
42 is obj = db_model.query.filter_by (** Filters ) .first ()
43 is Print (obj)
Referring to the document:
Flask-SQLALchemy filter_by dynamic filter and
Clear they want to find in the end what is the problem (it is dynamic access model name) from the article
Dynamic binding flask-sqlalchemy of model
https://segmentfault.com/q/1010000011702302
Method of obtaining a reference model name: