当前位置:网站首页>Day6 --- Sqlalchemy advanced
Day6 --- Sqlalchemy advanced
2022-07-27 08:29:00 【qishaoawei】
Single table data query
stay model.py Create model class in file
from flask_sqlalchemy import SQLAlchemy # Import
db=SQLAlchemy() # Instantiate database connection object
# Create model classes
class UserModel(db.Model):
# primary_key Primary key autoincrement Self increasing default Default
id=db.Column(db.Integer,primary_key=True,autoincrement=True,comment='ID')
name=db.Column(db.String(32),default='',comment=' name ')
age=db.Column(db.Integer,default=0,comment=' Age ')
balance=db.Column(db.DECIMAL(10,2),comment=' assets ') # DECIMAL floating-point
Migrating data
Initialize migration file
python manage.py db init
Generate migration file
python manage.py db migrate
Perform the migration
python manage.py db upgrade
Migration completed
Realize the data addition and single table query of model classes in the blueprint
from flask import Blueprint # Import blueprint
from flask_restful import Api,Resource,fields,marshal
from models.model import UserModel, db
# # url_prefix # Specify the prefix of all routes under the current blueprint
user_dp=Blueprint('user_dp',__name__,url_prefix='/users') # Instantiate blueprint objects
api=Api(user_dp) # Instantiate the blueprint collector # Instantiate a Api object Api Object is used to collect routes
# Define class view Inherited from Resource class , adopt Api To collect instantiated objects
class UserView(Resource):
def get(self): # Test success
# Add data
u1=UserModel(
name=' Sicong ',age=12,balance=100,
)
u2=UserModel(
name=' The pony ',age=17,balance=100,
)
u3=UserModel(
name=' Old horse ',age=19,balance=1030,
)
db.session.add_all([u1,u2,u3])
db.session.commit()
return 'ssss'
# Add route
api.add_resource(UserView,'/user') # The full address is /users/user
filter(), filter_by Implement filter query operation
class UserView(Resource):
def get(self): # Test success
#lst=UserModel.query.all() # Query all
#filter(), filter_by Implement filtering operation The two methods work the same
#lst=UserModel.query.filter(UserModel.name==' Old horse ').first() #filter() Implement filtering operation
lst=UserModel.query.filter_by(name=' Old horse ').first() #filter_by Implement filtering operation
print(lst)
Paging and sorting
class UserView(Resource):
def get(self): # Test success
# Pagination Sort data
# first page 0,2 # the number of pages -1 * Number of entries per page
# The second page 2,2
# The third page 4,2
# page=2
# page_size=2
## Skip the second query , Limit output 2 strip
# UserModel.query.offset(offset).limit(page_size).all()
## Sort
## (1). Sort by age in ascending order , Default ascending order , It can be omitted ".asc()"
# UserModel.query.order_by(UserModel.age.asc()).all()
# (2). Sort by age
UserModel.query.order_by(UserModel.age.desc()).all()
Logical operations
class UserView(Resource):
def get(self): # Test success
from sqlalchemy import or_,and_,not_ # Guide pack
## Logical operations
lst=UserModel.query.filter(or_(UserModel.name==' Old horse ',UserModel.name==' The pony ')).all() # or
lst=UserModel.query.filter(and_(UserModel.name==' Old horse ',UserModel.age==19)).all() # And
lst=UserModel.query.filter(not_(UserModel.name==' Old horse ')).all() # Not
print(lst)
Comparison query
class UserView(Resource):
def get(self): # Test success
## Comparison query
lst=UserModel.query.filter(UserModel.age.__lt__(18)).all() # Less than
lst=UserModel.query.filter(UserModel.age.__le__(18)).all() # Less than or equal to
lst=UserModel.query.filter(UserModel.age.__gt__(18)).all() # Greater than
lst=UserModel.query.filter(UserModel.age.__ge__(18)).all() # Greater than or equal to
print(lst)
in Inquire about TODO in operation
class UserView(Resource):
def get(self): # Test success
# in Inquire about TODO in operation
lst=UserModel.query.filter(UserModel.name.in_((' The pony ',))).all() # It must be in the form of Yuanzu or list
return marshal(lst,{
'id':fields.Integer,
'name':fields.String,
'age':fields.Integer,
'balance':fields.Float
})
# Aggregate query
class UserView(Resource):
def get(self): # Test success
from sqlalchemy import func # Guide pack
# Aggregate query
lst=db.session.query(func.count(UserModel.id)).first()[0] # Count the number of data rows
lst=db.session.query(func.sum(UserModel.age)).first()[0] # Sum of Statistics
lst=db.session.query(func.avg(UserModel.age)).first()[0] # Statistical data please mean
print(lst)
Relationship query One-to-many relation
The establishment of a one to many relationship : One party establishes a relationship , Establish foreign keys by multiple parties
Create two tables The primary table is bound to the secondary table
stay model.py Create model class in file
Migrate after creation
from flask_sqlalchemy import SQLAlchemy # Import
db=SQLAlchemy() # Instantiate database connection object
# Professional model One to many model creation
class Sub(db.Model):
id=db.Column(db.Integer,primary_key=True,autoincrement=True,comment=' major ID')
name=db.Column(db.String(32),comment=' Major name ')
stu=db.relationship('Stu',backref='sub') # Declare a relationship with that model , There will be no substantive operations in the database
# Student model
class Stu(db.Model):
id=db.Column(db.Integer,primary_key=True,autoincrement=True,comment=' Student ID')
name=db.Column(db.String(32),comment=' Student name ')
age=db.Column(db.Integer,comment=' Student age ')
sub_id=db.Column(db.Integer,db.ForeignKey('sub.id')) # Declare a field , And the field is foreign key , Foreign keys are associated with that table
The blueprint realizes adding and querying data
from flask import Blueprint # Import blueprint
from flask_restful import Api,Resource,fields,marshal
from models.model import UserModel, db, Sub, Stu
# # url_prefix # Specify the prefix of all routes under the current blueprint
user_dp=Blueprint('user_dp',__name__,url_prefix='/users') # Instantiate blueprint objects
api=Api(user_dp) # Instantiate the blueprint collector # Instantiate a Api object Api Object is used to collect routes
# Define class view Inherited from Resource class , adopt Api To collect instantiated objects
class UserView(Resource):
def get(self): # Test success
s1=Sub(name=' Artificial intelligence ')
s2=Sub(name=' Cutaway ')
s3=Sub(name=' Copy of the ')
stu1=Stu(name=' ha-ha ',age=18,sub=s1)
stu2=Stu(name=' Hey ',age=12,sub=s2)
stu3=Stu(name=' Hoho ',age=16,sub=s3)
db.session.add_all([s1,s2,s3])
db.session.add_all([stu1,stu2,stu3])
db.session.commit()
return 'sd'
# Add route
api.add_resource(UserView,'/user') # The full address is /users/user
. One to many queries
Is the query & Reverse query
class UserView(Resource):
def get(self): # Test success
# Is the query One party inquires information from many parties
sub_info=Sub.query.filter(Sub.name==' Artificial intelligence ').first()
print(sub_info.id)
for i in sub_info.stu: # Traverse the bound data
print(i.name,i.age)
# Reverse query Find out the information of one party from multiple parties
stu_info=Stu.query.filter(Stu.name==' ha-ha ').first()
print(stu_info.name,stu_info.age,stu_info.sub_id) # Display the queried data
print(stu_info.sub.name) # Print out the name of the binding foreign key
Relationship query Many to many relationship
The establishment of many to many relationship
1. First define two models that need to do many to many
2. Use Table Define an intermediate table , The intermediate table is generally the foreign key field containing two models , And let them both be one “ Composite primary key ”.
3. Choose one of the two models that need to do many to many , Define a relationship attribute , To bind the relationship between the three , In the use of relationship When , Need to pass in a secondary= Middle table model name .
stay model.py Create model classes in the file
Migrate after creation
# Create middle table
article_tag=db.Table(
'article_tag',
db.Column('article_id',db.Integer,db.ForeignKey('article.id'),primary_key=True),
db.Column('tag_id',db.Integer,db.ForeignKey('tag.id'),primary_key=True)
)
# Article table Many to many relationship
class Article(db.Model):
id=db.Column(db.Integer,primary_key=True,autoincrement=True,comment='Id')
title = db.Column(db.String(32), comment=' Article name ')
# Indicate two tables
tags=db.relationship('Tag',secondary=article_tag,backref='articles')
# The label table
class Tag(db.Model):
id=db.Column(db.Integer,primary_key=True,autoincrement=True,comment='Id')
name = db.Column(db.String(32), comment=' Tag name ')
The blueprint realizes the addition and query of data
Many to many add data
from flask import Blueprint # Import blueprint
from flask_restful import Api,Resource,fields,marshal
from models.model import UserModel, db, Sub, Stu, Article, Tag
# # url_prefix # Specify the prefix of all routes under the current blueprint
user_dp=Blueprint('user_dp',__name__,url_prefix='/users') # Instantiate blueprint objects
api=Api(user_dp) # Instantiate the blueprint collector # Instantiate a Api object Api Object is used to collect routes
# Define class view Inherited from Resource class , adopt Api To collect instantiated objects
class UserView(Resource):
def get(self): # Test success
## Many to many data add
t1=Tag(name='python') # First add foreign key data Add binding data
t2=Tag(name='java')
# db.session.commit() # After adding, comment this Then run the lower
# return ''
a1=Article(title=' artificial ',tags=[t1])
a2=Article(title=' data ',tags=[t2])
a3=Article(title=' The whole stack ',tags=[t1,t2])
# db.session.add_all([t1,t2])
db.session.add_all([a1,a2,a3])
db.session.commit()
# Add route
api.add_resource(UserView,'/user') # The full address is /users/user
Many to many queries
class UserView(Resource):
def get(self): # Test success
# Many-to-many queries Query all articles involved in a tag
tag_info=Tag.query.filter(Tag.name=='python').first()
print(tag_info.name)
print(tag_info.articles)
for i in tag_info.articles:
print(i.title) # You can query the binding foreign key name
# Query all the tags of the article
article_info=Article.query.filter(Article.id==2).first()
print(article_info.title)
print(article_info.tags) # View the data of the article table bound to itself
for i in article_info.tags:
print(i.name) # Query the other party's data
边栏推荐
- Introduction to depth first search (DFS)
- CMD command and NPM command
- I drew a Gu ailing with characters!
- Idea remote debugging
- [netding cup 2020 rosefinch group]nmap 1 two solutions
- Apache SSI remote command execution vulnerability
- Bandwidth and currency
- You may need an additional loader to handle the result of these loaders.
- Implementation of adding function of background user management display
- Netdata 性能监测工具介绍、安装、使用
猜你喜欢

regular expression

借生态力量,openGauss突破性能瓶颈

"PHP Basics" tags in PHP

我用字符画出了一个谷爱凌!
![[ciscn2019 southeast China division]web11 1](/img/94/61ad4f6cbbd46ff66f361462983d7a.png)
[ciscn2019 southeast China division]web11 1

Login to homepage function implementation

Block, there is a gap between the block elements in the row

Graph node deployment and testing

Teach you to build a nail warning robot hand in hand

Demo:st05 find text ID information
随机推荐
Realization of background channel group management function
regular expression
Plato farm is expected to further expand its ecosystem through elephant swap
openGauss之TryMe初体验
Vcenter7.0 managing esxi7.0 hosts
如何卸载--奇安信安全终端管理系统
arguments
All in one 1329 cells (breadth first search)
[uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100
Luogu super Mary game
ERP production operation control Huaxia
Realization of specification management and specification option management functions
"Intermediate and advanced test questions": what is the implementation principle of mvcc?
Attack and defense World Lottery
Iterators and generators
"PHP Basics" uses echo statements to output information
Leetcode54. Spiral matrix
Introduction to depth first search (DFS)
Solve the problem of slow batch insertion of MySQL JDBC data
Bandwidth and currency