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)
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
source share