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

Does SQLAlchemy provide a general way to get the primary key from a declaratively defined instance, so 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 
+6
source share
2 answers

You can use inspection for this purpose:

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

Passing an instance of the mapped object for validation returns an InstanceState describing this object. This condition 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 

It gives:

 (1,) 

Since primary keys can consist of several columns, the identifier is generally a tuple containing all the column values ​​that are part of the primary key. In your case, this is just key .

+10
source

If you need to get the primary keys of a class list rather than instance , the following describes how to do this.

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 an Inspect instance to return to all attribute names of each primary_key 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 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 
+5
source

Source: https://habr.com/ru/post/975526/


All Articles