python - 如何自动将数据库反射(reflect)到 sqlalchemy 声明性?

标签 python sqlalchemy

sqlautocode - 存在多对多关系问题

sqlsoup - 不支持关系

elixir - 笔记自动生成

还有什么我可以尝试的吗?

最佳答案

理论上,sqlalchemy 中的反射应该适合您。在这种情况下,我使用的是带有两个表的 mssql 数据库,这两个表具有简单的多对一关系:

带有字段的“测试”:

  • 身份证
  • 测试名称
  • author_id(Users 表的外键,Users.id 字段)

带有字段的“用户”:

  • 身份证
  • 全名

所以以下应该反射(reflect)数据库:

from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.schema import Table, MetaData
from sqlalchemy.ext.declarative import declarative_base

#Create and engine and get the metadata
Base = declarative_base()
engine = create_engine('put your database connect string here')
metadata = MetaData(bind=engine)

#Reflect each database table we need to use, using metadata
class Tests(Base):
    __table__ = Table('Tests', metadata, autoload=True)

class Users(Base):
    __table__ = Table('Users', metadata, autoload=True)

#Create a session to use the tables    
session = create_session(bind=engine)

#Here I will just query some data using my foreign key relation,  as you would
#normally do if you had created a declarative data mode.
#Note that not all test records have an author so I need to accomodate for Null records
testlist = session.query(Tests).all()    

for test in testlist:
    testauthor = session.query(Users).filter_by(id=test.author_id).first()  
    if not testauthor:
        print "Test Name: {}, No author recorded".format(test.testname)
    else:
        print "Test Name: {}, Test Author: {}".format(test.testname, testauthor.fullname)

所以这似乎适用于表关系。尽管您仍然没有详细说明您正在尝试做什么。

关于python - 如何自动将数据库反射(reflect)到 sqlalchemy 声明性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290162/

相关文章:

Python Pandas : How can I count the number of times a value appears in a column based upon another column?

python - 为什么我的 A* 搜索返回与 UniformCostSearch 相同的扩展空间?

python - Pandas 0.19.0explode() 解决方法

python - 在 SQLAlchemy 过滤器表达式中执行 "ilike or ilike"时出现类型错误

python - SQLAlchemy ORM 检查列是否为外键

python-3.x - 从 SQLAlchemy 结果返回字段名称和值

python - 想要在 django 模板中显示单词的第一个字符

Python 2.5 Windows 二进制文件?

python - 递归问题

python - SQLAlchemy 高级 count() 查询