57

I just want to programatically determine the name of an SQLalchemy model's primary key.

1
  • 6
    If this solution works for you, it's completely acceptable to add your solution as an answer and mark it as "answered". This helps for when people are looking for unanswered questions. Jul 20, 2011 at 7:48

4 Answers 4

68

If using SQLAlchemy version 0.8 or later, you should use the runtime inspection API.

If the model class is User and the sole primary key is id,

>>> from sqlalchemy.inspection import inspect
>>> inspect(User).primary_key[0].name
'id'

If the model class is User and there are many primary keys,

>>> from sqlalchemy.inspection import inspect
>>> [key.name for key in inspect(User).primary_key]
['id', 'name']

If using SQLAlchemy version less than 0.8, you should use the class_mapper() function instead.

>>> from sqlalchemy.orm import class_mapper
>>> class_mapper(User).primary_key[0].name
'id'

In this case, the inspect() function and the class_mapper() function return the same object, but using inspect() is more future-proof.

1
  • 1
    I know this is really old answer but it should be noted, all of the above return the column names which are not necessarily going to match the class property names. Mapper also has a method get_property_by_column which can be used to access the ColumnProperty object corresponding to the column in the primary key. ColumnProperty in turn gives you access to key, the name of the property, class_attribute to access the class InstrumentedAttribute, etc. Jul 30, 2021 at 13:01
9

If class is "User", and there is just 1 primary key, do this*:

User.__mapper__.primary_key._list[0].name

*Moved from the question.

1
  • Or if you need all the primary keys you can do the list comprehension stated above: [k.name for k in User.__mapper__.primary_key] Dec 12, 2018 at 10:01
2

Assuming the declarative model class is User,

>>> list(User.__table__.primary_key)[0].name
'id'

Or for Membership which has a composite primary key

>>> [pk.name for pk in Membership.__table__.primary_key]
['user_id', 'group_id']
1
  • Not sure why this has a negative vote when it works. Nov 11, 2019 at 12:09
1

For SQLAlchemy version 2.0, if you wish to know a table's primary key column name you will need to use inspect(table).primary_key.columns.values()[0].name as follows:

>>> metadata = MetaData(bind=engine)
>>> from sqlalchemy.inspection import inspect
>>> for table in metadata.sorted_tables:
>>>     if len(inspect(table).primary_key.columns.values()) > 0:
>>>          print("Table " + table.name + "'s primary key column is " + inspect(table).primary_key.columns.values()[0].name
Table x's primary key column is 'id'
Table y's primary key column is 'id' ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.