簡體   English   中英

當sqlalchemy ORM類屬性與數據庫列不同時,如何獲取ORM類屬性的列表?

[英]When the sqlalchemy ORM class attributes are different from database columns, how to get a list of the ORM class attributes?

假設您要遍歷sqlalchemy中ORM類的ORM屬性。 因此,您需要ORM屬性的列表。 您如何獲得該清單?

如果ORM類未重命名屬性,因此ORM屬性與數據庫列匹配,則可以使用以下解決方案: https : //stackoverflow.com/a/24748320/1023033 (順便說一句,還有一個內置的源代碼文件/lib/sqlalchemy/orm/base.py中的(私有)函數_orm_columns()似乎提供了此功能)

但是,如果python ORM類的名稱與數據庫列的名稱不同(例如,在這3個ORM屬性中):

>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column('pkey', Integer, primary_key=True)
...     name = Column('user_name', String)
...     fullname = Column('human_name', String)

那么該方法不起作用。 那么,如何獲得ORM屬性的python版本?

這已經使用檢查系統實現

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import inspect

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    x = Column(Integer)
    y = Column(Integer)

print inspect(A).c
print inspect(A).c.x
print inspect(A).column_attrs
print inspect(A).column_attrs.x
print inspect(A).column_attrs.x.expression

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

http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.all_orm_descriptors

http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.columns

http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.column_attrs

http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.c

我定義了一個mixin類來增強

Base = declarative_base()

mixin類的定義為:

import inspect
import sqlalchemy as sqla 

class orm_mixin_class(object):
    """Additional functionality wanted in orm classes (that inherit from Base)."""

    @classmethod
    def orm_class_info(cls):
        """
        Get info about the orm class (as opposed to the database table it is mapped to).

        Returns:
            list of dict where each dict describes a orm class attribute.  
            Keys: s_class_attribute_name
        """
        o_leaf_level_class = cls   # this turns out the be the leaf class instead of this mixin class
        l_orm_attribute_pairs = inspect.getmembers(o_leaf_level_class)

        l_orm_class_info_dicts = []
        for (s_class_attribute_name, o_attr_type) in l_orm_attribute_pairs:
            d_attr_info = {}
            b_orm_attribute = False
            try:
                o_inspect = sqla.inspection.inspect(o_attr_type) 

                if isinstance(o_inspect, sqla.orm.attributes.QueryableAttribute):
                    b_orm_attribute = True
                    d_attr_info['s_class_attribute_name'] = s_class_attribute_name
            except:
                pass            

            if b_orm_attribute:
                # only orm attributes have an entry in the output list
                l_orm_class_info_dicts.append(d_attr_info)

        return(l_orm_class_info_dicts)

因此,可以從方法調用中輕松獲得ORM屬性列表。

現在,ORM類聲明為:

class User(Base, orm_mixin_class):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM