简体   繁体   English

以编程方式访问 sqlalchemy 外键关系信息

[英]Accessing sqlalchemy Foreign Key relationship information programmatically

I'm trying to build tests for flask-sqlalchemy models to confirm they match the tables in the database.我正在尝试为flask-sqlalchemy 模型构建测试以确认它们与数据库中的表相匹配。 Using reflection, I can get the db tables, columns, and foreign keys.使用反射,我可以获得数据库表、列和外键。 With the models I know how to check tablename and column names, but I can't figure out how to see the defined foreign key relationships programatically.使用模型我知道如何检查表名和列名,但我无法弄清楚如何以编程方式查看定义的外键关系。

Model example:模型示例:

class Example(db.Model):
    __table_args__ = {'schema': 'defined_schema'}
    __tablename__ = 'example'

    id =          db.Column(db.BigInteger, primary_key=True)
    name =        db.Column(db.String)
    info =        db.Column(db.BigInteger, db.ForeignKey(Info.id))
    descr =       db.Column(db.String)

Given a Model m, I've tried:给定一个模型 m,我试过:

dir(m)
m.__dict__

使用sqlalchemy.inspect(model).columns.foreign_keys和一些字符串操作,我能够将模型外键关系与数据库中的关系进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM