在SQLAlchemy中从声明性定义的实例中获取主键的通用方法

时间:2014-09-19 10:46:51

标签: python sqlalchemy

SQLAlchemy是否提供了一种泛型方法来从声明性定义的实例中获取主键,因此如果:

Base = declarative_base()

class MyClass(Base):
    __tablename__ = 'mytable'
    key = Column(Integer, primary_key=True)

我能做到:

>>> a = MyClass(key=1)
>>> a.generic_get_primary_key()  # <-- does it exist ??
1

2 个答案:

答案 0 :(得分:12)

您可以将inspection用于此目的:

http://docs.sqlalchemy.org/en/latest/core/inspection.html

将映射对象的实例传递给inspect,返回InstanceState,描述该对象。 此状态还包含标识:

Base = declarative_base()

class MyClass(Base):
    __tablename__ = 'mytable'
    key = Column(Integer, primary_key=True)
a = MyClass(key=1)

from sqlalchemy.inspection import inspect    
pk = inspect(a).identity
print pk

会给:

(1,)

由于主键可以包含多个列,因此标识通常是一个元组,其中包含作为主键一部分的所有列值。 在您的情况下,这只是key

答案 1 :(得分:0)

我通过获取主键名称来实现,然后使用 getattr 传递类实例和主键名称,如下所示:does inherit CSP of parent document

from sqlalchemy.inspection import inspect

# I use this class for all my tables in sqlalchemy
class BaseTablesClass():
    # First I get the name of the primary key, just the first value of array because 
    # a table can have more than a primary key

    def primary_key_name(self):
        return inspect(self).primary_key[0].name

    # Next in this line I get the value of primary key by the name that I get with the
    # method of primary key name
    def primary_key_value(self):
        return getattr(self, self.primary_key_name())