relationship是为了简化联合查询join等,创建的两个表之间的虚拟关系,这种关系与标的结构时无关的。他与外键十分相似,确实,他必须在外键的基础上才允许使用

不然会报错:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Father.son - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression

详细的relationship可以点击这里进行查看

relationship的使用:

使两个表之间产生管理,类似于合成一张表,可以直接取出关联的表,进行获取数据,而不需要join操作

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer,ForeignKey
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("mysql+pymysql://root:root@127.0.0.1/t1")

Base = declarative_base()

class Father(Base):
    __tablename__ = "father"

    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(40),unique=True)
    age = Column(Integer)
    son = relationship('Son',backref="father")

class Son(Base):
    __tablename__ = 'son'

    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(40),unique=True)
    age = Column(Integer)

    father_id = Column(Integer,ForeignKey('father.id'))

Base.metadata.create_all(engine)

MySession = sessionmaker(bind=engine)
session = MySession()

# f = Father(name='ld',age=21)
# session.add(f)
# session.commit()
#
# s1 = Son(name='ww',age=1,father_id=1)
# s2 = Son(name='wb',age=0,father_id=1)
# session.add_all([s1,s2])
# session.commit()
#一对多情况下:多(包含外键方)

ret =session.query(Father).filter_by(id=1).first()
#ret.son 是一个列表,其中多的一方会获得一个列表结果,列表中含有其各个对象
for i in ret.son:
    print(i.name,i.age)


#另一方只会获得一个对象结果
ret2 = session.query(Son).filter_by(id=1).first()
print(ret2.father.name)#
原来代码,不需要看

相关文章: