当前位置:网站首页>[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 协程_Unity 协程的原理
- LeetCode 35. Search the insertion position - vector traversal (O (logn) and O (n) - binary search)
- 数据湖治理:优势、挑战和入门
- LNX efficient search engine, fastdeploy reasoning deployment toolbox, AI frontier paper | showmeai information daily # 07.04
- Solve the error of JSON module in PHP compilation and installation under CentOS 6.3
- 重排数组
- Temperature control system based on max31865
- 左右对齐!
- 31年前的Beyond演唱会,是如何超清修复的?
- Unity prefab day04
猜你喜欢

MySQL学习笔记——数据类型(2)

Redis 解决事务冲突之乐观锁和悲观锁

Big God explains open source buff gain strategy live broadcast

科普达人丨一文看懂阿里云的秘密武器“神龙架构”

Neuf tendances et priorités du DPI en 2022

The 17 year growth route of Zhang Liang, an open source person, can only be adhered to if he loves it

大神详解开源 BUFF 增益攻略丨直播

Deep learning network regularization
Redis哨兵模式实现一主二从三哨兵

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
随机推荐
Width and alignment
Redis shares four cache modes
js平铺数据查找叶子节点
Scientific research cartoon | what else to do after connecting with the subjects?
【学习笔记】拟阵
Unity script API - component component
%s格式符
selenium 元素交互
.Net之延迟队列
Weibo and Huya advance into interest communities: different paths for peers
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
进制形式
这几年爆火的智能物联网(AIoT),到底前景如何?
What is the future of the booming intelligent Internet of things (aiot) in recent years?
CentOS 6.3 下 PHP编译安装JSON模块报错解决
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
C1 certification learning notes 3 -- Web Foundation
【大连理工大学】考研初试复试资料分享
科研漫画 | 联系到被试后还需要做什么?