003-sqlalchemy-外键与relationship的关系

使用外键与relationship,可以完成两个张表的关联。

如下例,son表中father_id外键关联到father表中id.

通过在father表对象中添加son这个relationship。

就实现了从一个father对象查询的结果中读取到son对象中的内容。

同时也可以实现从son对象来读取father对象内容。

 1 import sqlalchemy
 2 from sqlalchemy import create_engine
 3 from sqlalchemy import Column,String,Integer,ForeignKey
 4 from sqlalchemy.orm import sessionmaker,relationship
 5 from sqlalchemy.ext.declarative import declarative_base
 6 
 7 engine = create_engine("mysql+pymysql://root:root123@192.168.10.241/oldboydb2?charset=utf8")
 8 
 9 Base = declarative_base()
10 
11 class Father(Base):
12     __tablename__ = "father"
13 
14     id = Column(Integer,primary_key=True,autoincrement=True)
15     name = Column(String(40),unique=True)
16     age = Column(Integer)
17     son = relationship('Son',backref="father")
18     #son = relationship('Son')
19 
20 class Son(Base):
21     __tablename__ = 'son'
22 
23     id = Column(Integer,primary_key=True,autoincrement=True)
24     name = Column(String(40),unique=True)
25     age = Column(Integer)
26     #father = relationship('Father')
27 
28     father_id = Column(Integer,ForeignKey('father.id'))
29 
30 # Base.metadata.create_all(engine)
31 
32 MySession = sessionmaker(bind=engine)
33 session = MySession()
34 
35 ret = session.query(Father).filter_by(id=1).first()
36 print(ret.son[0].name) #多个结果[<__main__.Son object at 0x0000000003F192B0>,
37 # <__main__.Son object at 0x0000000003F19320>]
38 #需要循环取值
39 
40 ret = session.query(Son).filter_by(id=1).first()
41 print(ret.father.name)#一个结果<__main__.Father object at 0x0000000003F196D8>
42 #直接取值
原文地址:https://www.cnblogs.com/zhidian2020/p/14010588.html