Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of an SQLAlchemy object's primary key?

Tags:

sqlalchemy

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

like image 988
Peter Avatar asked Jul 19 '11 09:07

Peter


People also ask

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

How do you find the primary key in Python?

The model primary key Field can be obtained via the StdModel.pk() class method. A model can have one and only one primary key which is specified by passing primary_key=True during model definition: class MyModel(odm. StdModel): id = odm.

What is primary key in Flask SQLAlchemy?

Most ORMs require that objects have some kind of primary key defined because the object in memory must correspond to a uniquely identifiable row in the database table; at the very least, this allows the object can be targeted for UPDATE and DELETE statements which will affect only that object's row and no other.

Does SQLAlchemy require primary key?

¶ The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well.


3 Answers

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.

like image 143
argentpepper Avatar answered Oct 07 '22 10:10

argentpepper


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

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

*Moved from the question.

like image 44
Bill the Lizard Avatar answered Oct 07 '22 08:10

Bill the Lizard


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']
like image 36
Frozen Flame Avatar answered Oct 07 '22 10:10

Frozen Flame