Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to get primary key from declaratively defined instance in SQLAlchemy

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
like image 971
frip Avatar asked Sep 19 '14 10:09

frip


2 Answers

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.

like image 87
sebastian Avatar answered Nov 05 '22 13:11

sebastian


If you need to retrieve a list primary keys of a class not an instance the following describes how to do it.

You can use the inspect method. This will return an Inspect instance on which you can do your analysis as follows. In this example I use the Inspect instance to return to me all attribute names of each primary_key of MyClass.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class MyClass(Base):
    __tablename__ = "myclass"

    key = Column(Integer, primary_key=True)
    name = Column(String, primary_key=True)



from sqlalchemy import inspect
ins = inspect(MyClass)
print("Tuple of primary keys: ", ins.primary_key)

# Let's loop over them and print the attribute key name of each
for x in ins.primary_key:
    print(x.key)

Returns

> Tuple of primary keys:  (Column('key', Integer(), table=<myclass>, primary_key=True, nullable=False), Column('name', String(), table=<myclass>, primary_key=True, nullable=False))
> key
> name
like image 35
flazzarini Avatar answered Nov 05 '22 13:11

flazzarini