当前位置:网站首页>[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)
边栏推荐
- How did the beyond concert 31 years ago get super clean and repaired?
- lnx 高效搜索引擎、FastDeploy 推理部署工具箱、AI前沿论文 | ShowMeAI资讯日报 #07.04
- Preliminary exploration of flask: WSGI
- MySQL学习笔记——数据类型(数值类型)
- Unity脚本介绍 Day01
- 【读书会第十三期】FFmpeg 查看媒体信息和处理音视频文件的常用方法
- Unity动画Animation Day05
- Unity script introduction day01
- [Dalian University of technology] information sharing of postgraduate entrance examination and re examination
- 进制乱炖
猜你喜欢
Redis sentinel mode realizes one master, two slave and three Sentinels
【大连理工大学】考研初试复试资料分享
Live broadcast preview | PostgreSQL kernel Interpretation Series II: PostgreSQL architecture
科普达人丨一文看懂阿里云的秘密武器“神龙架构”
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
Guitar Pro 8win10 latest guitar learning / score / creation
数据湖治理:优势、挑战和入门
31年前的Beyond演唱会,是如何超清修复的?
MySQL learning notes - data type (2)
Optimization method of deep learning neural network
随机推荐
LeetCode 58. Length of the last word
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
hexadecimal
MP3是如何诞生的?
MYSQL索引优化
Optimization method of deep learning neural network
Redis publish and subscribe
输入宽度!
MySQL学习笔记——数据类型(2)
Go deep into the details of deconstruction and assignment of several data types in JS
They are all talking about Devops. Do you really understand it?
Unity动画Animation Day05
[book club issue 13] packaging format and coding format of audio files
Unity脚本常用API Day03
Deep learning network regularization
AI做题水平已超过CS博士?
Unity animation day05
LeetCode 35. Search the insertion position - vector traversal (O (logn) and O (n) - binary search)
每周招聘|高级DBA年薪49+,机会越多,成功越近!
.Net 应用考虑x64生成