Does SQLAlchemy offer a generic way to get the primary key from a declaratively defined instance, so that if:
Base = declarative_base()class MyClass(Base):__tablename__ = 'mytable'key = Column(Integer, primary_key=True)
I can do:
>>> a = MyClass(key=1)
>>> a.generic_get_primary_key() # <-- does it exist ??
1
You can use inspection
for that purpose:
http://docs.sqlalchemy.org/en/latest/core/inspection.html
Passing an instance of a mapped object to inspect, returns an InstanceState
, describing that object.
This state also contains the identity:
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
Will give:
(1,)
Since primary keys can consist of multiple columns, the identity in general is a tuple containing all the column values that are part of the primary key.
In your case, that's simply the key
.