automap

Posted 台灯不太亮

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:[email protected]/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:[email protected]/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)

以上是关于automap的主要内容,如果未能解决你的问题,请参考以下文章

automap

[Pythod][Sqlalchemy]Automap 实践

使用 Fluent NHibernate AutoMapping 进行级联保存

Castle Windsor、Fluent Nhibernate 和 Automapping Isession 关闭问题

sqlalchemy 如何使用 automap_base 生成(多对多)关系

SQLAlchemy AutoMap AttributeError(尽管定义了主键)