当前位置:网站首页>[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)
边栏推荐
- Stew in disorder
- Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
- C1 certification learning notes 3 -- Web Foundation
- Redis publish and subscribe
- 夜天之书 #53 Apache 开源社群的“石头汤”
- AI做题水平已超过CS博士?
- JS tile data lookup leaf node
- 干货 | fMRI标准报告指南新鲜出炉啦,快来涨知识吧
- 华为云数据库DDS产品深度赋能
- Unity脚本API—Time类
猜你喜欢

Intelligent customer service track: Netease Qiyu and Weier technology play different ways

Guitar Pro 8win10 latest guitar learning / score / creation

Unity script lifecycle day02

Unity动画Animation Day05

What is the future of the booming intelligent Internet of things (aiot) in recent years?

华为云数据库DDS产品深度赋能

中国主要城市人均存款出炉,你达标了吗?

Unity脚本生命周期 Day02

I plan to teach myself some programming and want to work as a part-time programmer. I want to ask which programmer has a simple part-time platform list and doesn't investigate the degree of the receiv

Unity脚本常用API Day03
随机推荐
[book club issue 13] packaging format and coding format of audio files
华为云数据库DDS产品深度赋能
Live broadcast preview | PostgreSQL kernel Interpretation Series II: PostgreSQL architecture
Optimization method of deep learning neural network
Width and alignment
JS tile data lookup leaf node
What encryption algorithm is used for the master password of odoo database?
How did the beyond concert 31 years ago get super clean and repaired?
Understand the context in go language in an article
数据湖治理:优势、挑战和入门
LeetCode 58. Length of the last word
输入宽度!
2022年九大CIO趋势和优先事项
小数,指数
左右对齐!
基于MAX31865的温度控制系统
Guitar Pro 8win10 latest guitar learning / score / creation
The 17 year growth route of Zhang Liang, an open source person, can only be adhered to if he loves it
The per capita savings of major cities in China have been released. Have you reached the standard?
宽度与对齐