当前位置:网站首页>[flask] ORM one to many relationship
[flask] ORM one to many relationship
2022-07-04 15:41:00 【YZL40514131】
SQLAlchemy Provides a relationship, This class can define attributes , In the future, when accessing the associated table, you can access it directly through attribute access . in addition , Can pass backref To specify the attribute name of reverse access .
Configuration database 、 Create database engine 、 Create base class
# Configuration database
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test'
USERNAME = 'root'
PASSWORD = 'root'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
# Create database engine
engine=create_engine(DB_URI)
# Create base class , All model classes inherit the base class
Base=declarative_base(engine)
# establish session
session=sessionmaker(engine)()
Method 1 :
Create model classes
# Create model classes
class Dept(Base):
__tablename__='t_dept2'
dept_no=Column(name='dept_no',type_=Integer,primary_key=True,autoincrement=True)
dept_name=Column(name='dept_name',type_=String(20))
city=Column(name='city',type_=String(20))
# Represents the list of all employees in the current department , This way of writing is not the best , The best way to write is to associate in an object
emp=relationship('Emp') # The parameter must be the class name of another association model class
def __str__(self):
return f' Department number :{
self.dept_no} department :{
self.dept_name} City :{
self.city}'
Particular attention 1: The first 9 Line code : Represents the list of all employees in the current department ; This way of writing is not the best , The best way to write is to associate in an object
class Emp(Base):
__tablename__='t_emp2'
emp_no=Column(name='emp_no',type_=Integer,primary_key=True,autoincrement=True)
emp_name=Column(name='emp_name',type_=String(20))
hire_date=Column(name='hire_date',type_=DATE)
sal=Column(name='sal',type_=DECIMAL(10,2))
#todo Set the foreign key association , Add a field from the table , Specify which field of the table is the foreign key of this field . From the field of the foreign key in the table , It must be consistent with the primary key field type of the main table .
dept_no=Column(ForeignKey('t_dept2.dept_no',ondelete='CASCADE'),name='dept_no',type_=Integer)
# Information of the Department to which the employee belongs
dept=relationship('Dept') # The parameter must be the class name of another association model class
def __str__(self):
return f' Employee number :{
self.emp_no} Employee name :{
self.emp_name} The employee's entry time :{
self.hire_date} Employee pay :{
self.sal}'
Particular attention 2: Set the foreign key association , Add a field from the table , Specify which field of the table is the foreign key of this field . From the field of the foreign key in the table , It must be consistent with the primary key field type of the main table .
dept_no=Column(ForeignKey('t_dept2.dept_no',ondelete='CASCADE'),name='dept_no',type_=Integer)
Method 2 : Comment the ninth line of code in method one , Just associate in a model class
# Create model classes
class Dept(Base):
__tablename__='t_dept2'
dept_no=Column(name='dept_no',type_=Integer,primary_key=True,autoincrement=True)
dept_name=Column(name='dept_name',type_=String(20))
city=Column(name='city',type_=String(20))
# Represents the list of all employees in the current department , This way of writing is not the best , The best way to write is to associate in an object
#emp=relationship('Emp') # The parameter must be the class name of another association model class
def __str__(self):
return f' Department number :{
self.dept_no} department :{
self.dept_name} City :{
self.city}'
class Emp(Base):
__tablename__='t_emp2'
emp_no=Column(name='emp_no',type_=Integer,primary_key=True,autoincrement=True)
emp_name=Column(name='emp_name',type_=String(20))
hire_date=Column(name='hire_date',type_=DATE)
sal=Column(name='sal',type_=DECIMAL(10,2))
#todo Set the foreign key association , Add a field from the table , Specify which field of the table is the foreign key of this field . From the field of the foreign key in the table , It must be consistent with the primary key field type of the main table .
dept_no=Column(ForeignKey('t_dept2.dept_no',ondelete='CASCADE'),name='dept_no',type_=Integer)
# Information of the Department to which the employee belongs ,backref: Reverse associated attribute name
dept=relationship('Dept',backref='emp') # The parameter must be the class name of another association model class
def __str__(self):
return f' Employee number :{
self.emp_no} Employee name :{
self.emp_name} The employee's entry time :{
self.hire_date} Employee pay :{
self.sal}
Particular attention 3: The first 12 Line code : Information of the Department to which the employee belongs ,backref: Reverse associated attribute name ,dept=relationship('Dept',backref='emp')
Medium Dept
It must be another associated class name
Particular attention 4:relationship,backref Import required from sqlalchemy.orm import sessionmaker,relationship,backref
insert data
def save():
d1=Dept(dept_name=' Information Department ',city=' Beijing ')
session.add(d1)
#session.commit()
e1=Emp(emp_name='python',hire_date='2020-1-1',sal='8888.88',dept_no=1)
session.add(e1)
session.commit()
Query data :
Inquire about 1: Check all employees in the finance department
d1=session.query(Dept).filter(Dept.dept_name==' Finance Department ').first()
print(d1)
for i in d1.emp:
print(i)
Department number :2 department : City of Finance Department : Shanghai
Employee number :5 Employee name :flask The employee's entry time :2022-02-06 Employee pay :7777.77
Employee number :6 Employee name :django The employee's entry time :2021-12-12 Employee pay :10000.00
Inquire about 2: Query the information that the entry time of employees under the Department is greater than 2022 year , And the salary exceeds 8000 Employee information
d2=session.query(Emp).filter(Dept.dept_name==' Information Department ').filter(Emp.hire_date>'2022-01-01',Emp.sal>8000).first()
print(d2)
Employee number :4 Employee name :jmeter The employee's entry time :2022-06-04 Employee pay :10000.00
Inquire about 3: Inquire about python The employee's Department
e1=session.query(Emp).filter(Emp.emp_name=='python').first()
print(e1)
print(e1.dept)
Inquire about 4: Query employees whose employment time is greater than 2022 year , And the salary exceeds 7000 Of the employees are in those departments
e2=session.query(Dept).filter(Emp.hire_date>'2022-1-1',Emp.sal>7000).all()
print(e2)
for i in e2:
print(i)
[<__main__.Dept object at 0x000001BA5EF8BCA0>, <__main__.Dept object at 0x000001BA5EF8BF40>]
Department number :1 department : Ministry of information city : Beijing
Department number :2 department : City of Finance Department : Shanghai
Inquire about 5: Statistics on the Department of the highest paid employees
res13=session.query(Emp,func.max(Emp.sal)).first()[0] # Employee number :2~ Employee name :james~ come from : Beijing ~ Salary :50000.00
print(res13)
print(type(res13)) #Emp object , You can call properties
print(res13.dept)
Update data
Number the employee in the employee table as 18 The number of employees in the Department where the employee information is located is changed to 500
def update():
res1=session.query(Emp).filter(Emp.emp_id==18).first()
print(res1)
res2=res1.dept
print(type(res2)) #<class '__main__.Dept'>
res2.emp_count=500
session.commit()
doubt : I need some advice from bloggers :
problem : Statistics of the highest paid employees in each department , How to modify the following code ???
res15=session.query(Emp,func.max(Emp.sal)).group_by(Emp.dept_id).all()
print(res15)
边栏推荐
- Unity update process_ Principle of unity synergy
- Halcon knowledge: NCC_ Model template matching
- Functional interface, method reference, list collection sorting gadget implemented by lambda
- 2022年九大CIO趨勢和優先事項
- Analysis of nearly 100 million dollars stolen and horizon cross chain bridge attacked
- Redis的4种缓存模式分享
- 暑期复习,一定要避免踩这些坑!
- Go deep into the details of deconstruction and assignment of several data types in JS
- 案例分享|金融业数据运营运维一体化建设
- Introduction of text mining tools [easy to understand]
猜你喜欢
Unity animation day05
Dialogue with ye Yanxiu, senior consultant of Longzhi and atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?
Lombok使用引发的血案
C1 certification learning notes 3 -- Web Foundation
Blood cases caused by Lombok use
.Net 应用考虑x64生成
Neuf tendances et priorités du DPI en 2022
In today's highly integrated chips, most of them are CMOS devices
开源人张亮的 17 年成长路线,热爱才能坚持
Big God explains open source buff gain strategy live broadcast
随机推荐
函数式接口,方法引用,Lambda实现的List集合排序小工具
基于MAX31865的温度控制系统
lnx 高效搜索引擎、FastDeploy 推理部署工具箱、AI前沿论文 | ShowMeAI资讯日报 #07.04
MySQL学习笔记——数据类型(2)
[book club issue 13] ffmpeg common methods for viewing media information and processing audio and video files
Data Lake Governance: advantages, challenges and entry
暑期复习,一定要避免踩这些坑!
MySQL学习笔记——数据类型(数值类型)
hexadecimal
小数,指数
MySQL - MySQL adds self incrementing IDs to existing data tables
Redis的4种缓存模式分享
Intelligent customer service track: Netease Qiyu and Weier technology play different ways
宽度精度
Unity script lifecycle day02
web聊天室实现
Solve the error of JSON module in PHP compilation and installation under CentOS 6.3
Redis shares four cache modes
LNX efficient search engine, fastdeploy reasoning deployment toolbox, AI frontier paper | showmeai information daily # 07.04
科普达人丨一文看懂阿里云的秘密武器“神龙架构”