如何获取 SQLAlchemy 对象的主键的名称? [英] How do I get the name of an SQLAlchemy object's primary key?
问题描述
我只想以编程方式确定 SQLalchemy 模型的主键的名称.
如果使用 SQLAlchemy 0.8 或更高版本,您应该使用 运行时检查 API.
如果模型类是User
,唯一的主键是id
,
如果模型类是User
并且有很多主键,
如果使用低于 0.8 的 SQLAlchemy 版本,则应改用 class_mapper()
函数.
在这种情况下,inspect()
函数和 class_mapper()
函数返回相同的对象,但使用 inspect()
是更具前瞻性.
I just want to programatically determine the name of an SQLalchemy model's primary key.
If using SQLAlchemy version 0.8 or later, you should use the runtime inspection API.
If the model class is User
and the sole primary key is id
,
>>> from sqlalchemy.inspection import inspect
>>> inspect(User).primary_key[0].name
'id'
If the model class is User
and there are many primary keys,
>>> from sqlalchemy.inspection import inspect
>>> [key.name for key in inspect(User).primary_key]
['id', 'name']
If using SQLAlchemy version less than 0.8, you should use the class_mapper()
function instead.
>>> from sqlalchemy.orm import class_mapper
>>> class_mapper(User).primary_key[0].name
'id'
In this case, the inspect()
function and the class_mapper()
function return the same object, but using inspect()
is more future-proof.
这篇关于如何获取 SQLAlchemy 对象的主键的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!