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/