当前位置:网站首页>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
边栏推荐
- 众昂矿业:新能源行业快速发展,氟化工产品势头强劲
- Realization of backstage brand management function
- Realization of background channel group management function
- ERP production operation control Huaxia
- Design and development of GUI programming for fixed-point one click query
- Alibaba cloud international receipt message introduction and configuration process
- 【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发1/100
- After installing mysql, docker entered the container and found that he could not log in to MySQL
- Implementation of adding function of background user management display
- 我用字符画出了一个谷爱凌!
猜你喜欢

说透缓存一致性与内存屏障

Attack and defense World Lottery

Virtual machine cloning

众昂矿业:新能源行业快速发展,氟化工产品势头强劲

The third letter to the little sister of the test | Oracle stored procedure knowledge sharing and test instructions

Vcenter7.0 managing esxi7.0 hosts

pytorch_demo1

DEMO:ST05 找文本ID 信息

Use of "PHP Basics" delimiters

阿里云国际版回执消息简介与配置流程
随机推荐
"PHP Basics" tags in PHP
我用字符画出了一个谷爱凌!
[uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100
CMD command and NPM command
Map structure
[MRCTF2020]PYWebsite 1
JS basic exercises
Installation and use of beef XSS
Database startup report error_ user_ connect_ times > 0 error
2022/7/26 exam summary
Teach you to build a nail warning robot hand in hand
信息化项目风险控制与应用
Background coupon management
STM32 small bug summary
Chapter 2 foreground data display
[NPUCTF2020]ReadlezPHP 1
Element display mode: block level, inline, inline block, nesting specification, display mode conversion
Virtual machine cloning
List delete collection elements
Creation and simple application of QPushButton button button