通过查询多个父亲,对应一个儿子
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine Base = declarative_base()
engine = create_engine('mysql+pymysql://root:[email protected]:3306/day11',echo=True) class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(String(64))
child_id = Column(Integer, ForeignKey("child.id"))
childr = relationship("Child") class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
name = Column(String(64)) Base.metadata.create_all(engine) DBSession = sessionmaker()
DBSession.configure(bind=engine)
session = DBSession() # 打开数据连接 ret = session.query(Parent).filter(Parent.name == 'zeng').one()
print(ret)
print(ret.childr.name)
ret = session.query(Parent).filter(Parent.name == 'chunyun').one()
print(ret)
print(ret.childr.name) ret = session.query(Parent).filter(Parent.name == 'chun').one()
print(ret)
print(ret.childr.name)
many to one 第二式
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(String(64))
child_id = Column(Integer, ForeignKey("child.id"))
childr = relationship("Child", back_populates="parents") class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
name = Column(String(64))
parents = relationship("Parent", back_populates="childr")找到父亲 #通过双向建立映射关系,能让父亲查到儿子,也能让儿子
many to one 终极版
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(String(64))
child_id = Column(Integer, ForeignKey("child.id"))
childr = relationship("Child", backref="parents") # 这段代码,变相的等于在Child类中添加了parents = relationship("Parent", back_populates="childr") class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
name = Column(String(64))