码迷,mamicode.com
首页 > 其他好文 > 详细

automap

时间:2017-01-18 10:58:46      阅读:362      评论:0      收藏:0      [点我收藏+]

标签:com   init   string   需要   class   als   odi   user   pre   


一、事先定义的表结构
  • 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)

automap

标签:com   init   string   需要   class   als   odi   user   pre   

原文地址:http://www.cnblogs.com/qiaogy/p/6295672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!