确定属性是否为sqlalchemy中的backref

Ask*_*ken 5 python sqlalchemy

我在模型中设置了以下关系:

role_profiles = Table('roleprofile', Base.metadata,
                  Column('role_id', Integer, ForeignKey('role.id')),
                  Column('profile_id', Integer, ForeignKey('profile.id'))
                  )

class profile(Base):
    __tablename__ = 'profile'

    # Columns...

    roles = relationship('role', secondary=role_profiles, backref='profiles')


class role(Base):
    __tablename__ = 'role'

    # Columns...
Run Code Online (Sandbox Code Playgroud)

所以我现在明白它的工作原理是profile对象上的roles属性将包含一个角色类列表(它所做的).

我想要做的是一般地序列化模型类的每个属性.它适用于顶级配置文件,我确定有一个列表roles,我应该递归到:

# I need a statement here to check if the field.value is a backref
#if field.value is backref:
#    continue

if isinstance(field.value, list):
    # Get the json for the list
    value = serialize.serialize_to_json(field.value)
else:
    # Get the json for the value
    value = cls._serialize(field.value)
Run Code Online (Sandbox Code Playgroud)

问题是backref关系的关系会将指针添加回配置文件.然后序列化相同的配置文件,并一遍又一遍地重复角色,直到stack overflow.

有没有办法确定该属性是backrefrelationship?添加的?

更新

也许我应该补充一点,在这种情况下它可以正常工作,如果我删除,backref因为我不需要它,但我想保留它.

更新

作为临时修复,我向我的基类添加了一个类属性:

class BaseModelMixin(object):
    """Base mixin for models using stamped data"""

    __backref__ = None
Run Code Online (Sandbox Code Playgroud)

并添加如下:

class role(Base):
    __tablename__ = 'role'
    __backref__ = ('profiles', )

    # Columns...
Run Code Online (Sandbox Code Playgroud)

并在我的递归中使用它:

if self.__backref__ and property_name in self.__backref__:
    continue
Run Code Online (Sandbox Code Playgroud)

如果有更好的方法请告诉我,因为这看起来并不理想.

sec*_*ond 2

看一下inspect

例如

from sqlalchemy import inspect
mapper = inspect(MyModelClass)
# dir(mapper)
# mapper.relationships.keys()
Run Code Online (Sandbox Code Playgroud)