如何从 SQLAlchemy 映射对象中发现表属性

2023-10-10数据库问题
1

本文介绍了如何从 SQLAlchemy 映射对象中发现表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个用表映射的类,在我的例子中是声明式的,我想从这个类中发现"表属性、列、名称、关系:

I have a class mapped with a table, in my case in a declarative way, and I want to "discover" table properties, columns, names, relations, from this class:

engine = create_engine('sqlite:///' + databasePath, echo=True)

# setting up root class for declarative declaration
Base = declarative_base(bind=engine)

class Ship(Base):
    __tablename__ = 'ships'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))

    def __init__(self, name):
            self.name = name

    def __repr__(self):
            return "<Ship('%s')>" % (self.name)

所以现在我的目标是从Ship"类从另一段代码中获取表列及其属性.我想我可以使用检测来处理它,但是 SQLAlchemy API 是否提供了任何方法?

So now my goal is from the "Ship" class to get the table columns and their properties from another piece of code. I guess I can deal with it using instrumentation but is there any way provided by the SQLAlchemy API?

推荐答案

您需要的信息可以从 表 对象:

Information you need you can get from Table object:

  • Ship.__table__.columns 将为您提供栏目信息
  • Ship.__table__.foreign_keys 将列出外键
  • Ship.__table__.constraintsShip.__table__.indexes 是您可能会觉得有用的其他属性
  • Ship.__table__.columns will provide you with columns information
  • Ship.__table__.foreign_keys will list foreign keys
  • Ship.__table__.constraints, Ship.__table__.indexes are other properties you might find useful

这篇关于如何从 SQLAlchemy 映射对象中发现表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用Python+SQLAlchemy远程连接MySQL数据库?
How to connect MySQL database using Python+SQLAlchemy remotely?(如何使用Python+SQLAlchemy远程连接MySQL数据库?)...
2024-04-16 数据库问题
15

在 SQLite 中按月分组
Group by month in SQLite(在 SQLite 中按月分组)...
2024-04-16 数据库问题
6

Python 中参数查询的语法 (pyodbc)
Syntax for a parameter query in Python (pyodbc)(Python 中参数查询的语法 (pyodbc))...
2024-04-15 数据库问题
11

如何从 Python 中的数据库创建 CSV 文件?
How do I create a CSV file from database in Python?(如何从 Python 中的数据库创建 CSV 文件?)...
2024-04-15 数据库问题
3

SQLite3 和多个进程
SQLite3 and multiple processes(SQLite3 和多个进程)...
2024-04-15 数据库问题
5

如何使用 RSqlite 将 CSV 导入 sqlite?
How to import CSV into sqlite using RSqlite?(如何使用 RSqlite 将 CSV 导入 sqlite?)...
2023-11-28 数据库问题
6