automap
一、事先定义的表结构
- db_init.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker engine = create_engine("mysql+pymysql://root:redhat@192.168.10.209/db01?charset=utf8") Base = declarative_base() class Student(Base): __tablename__ = 'student' id = Column(Integer, primary_key=True) name = Column(String(32), nullable=False) address = relationship('Address', backref='student') class Address(Base): __tablename__ = 'address' id = Column(Integer, primary_key=True) u_id = Column(Integer, ForeignKey('student.id')) name = Column(String(32), nullable=False) # Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) session_cls = sessionmaker(bind=engine) session = session_cls() session.add_all([ Student(name='user1'), Student(name='user2'), Student(name='user3'), Address(u_id=1, name='add-1'), Address(u_id=2, name='add-2'), Address(u_id=3, name='add-3'), Address(u_id=3, name='add-4'), ]) # session.commit() # 利用 backref查找,成功 ret = session.query(Address).filter(Address.u_id == 1).first().student.name print(ret)
二、不知道表结构
- automap.py # 注意,此处只是一对多,反射到了releastionsip,多对多没有测试成功,但是官网说可以
#!/usr/bin/env python # -*- coding:utf-8 -*- import random from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy.orm import relationship from sqlalchemy import create_engine # 初始化一个automap类 Base = automap_base() engine = create_engine("mysql+pymysql://root:redhat@192.168.10.209/db01?charset=utf8") Base.prepare(engine, reflect=True) # 反射所有的表 session = Session(engine) Student = Base.classes.student # 获取所需要的表 Address = Base.classes.address
# 利用表的backref 成功获取结果 ret = session.query(Address).filter(Address.u_id == 1).first().student.name print(ret)