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

后端 未结 3 759
一整个雨季
一整个雨季 2020-12-24 05:13

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

相关标签:
3条回答
  • 2020-12-24 05:38

    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']
    
    0 讨论(0)
  • 2020-12-24 05:42

    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.

    0 讨论(0)
  • 2020-12-24 05:48

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

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

    *Moved from the question.

    0 讨论(0)
提交回复
热议问题