Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确定属性是否为sqlalchemy中的backref_Python_Sqlalchemy - Fatal编程技术网

Python 确定属性是否为sqlalchemy中的backref

Python 确定属性是否为sqlalchemy中的backref,python,sqlalchemy,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):

我在模型中建立了以下关系:

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...
因此,我现在了解到,它的工作原理是profile对象上的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)
问题是关系的
backref
添加了一个指向概要文件的指针。然后对同一个概要文件进行序列化,并一次又一次地递归角色,直到
堆栈溢出

是否有方法确定该属性是由
关系添加的
backref

更新

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

更新

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

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

    __backref__ = None
并添加如下内容:

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

    # Columns...
在我的递归中这样使用它:

if self.__backref__ and property_name in self.__backref__:
    continue
如果有更好的方法,请告诉我,因为这看起来并不理想。

看看

e、 g


您可以在类
BaseModelMixin
中创建一个
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
作为
@属性,该属性包含一个列表,其中列出了所有在模型中不作为backref名称的关系名称

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

    @property
    def __relationships__(self):  
        """
        Return a list of relationships name which are not as a backref
        name in model    
        """
        back_ref_relationships = list()
        items = self.__mapper__.relationships.items()
        for (key, value) in items:
            if isinstance(value.backref, tuple):
                back_ref_relationships.append(key)
        return back_ref_relationships
由于您有两个class
profile
role
,所以

>>> p = profile()
>>> p.__relationships__
    # ['roles']

>>> r = role()
>>> r.__relationships__
   # []

不确定这是否是最佳实践,但这段代码对我适用。如果属性是引用,则返回True;如果是常规列类型,则返回False

def is_relation(orm_object, attr_name):
    return hasattr(getattr(orm_object.__class__, attr_name).property, 'mapper')

行。我会回来的。。。谢谢小心不要与Python的内置
inspect
Great-response冲突!sqlalchemy应该让识别回溯和关系变得更容易。
def is_relation(orm_object, attr_name):
    return hasattr(getattr(orm_object.__class__, attr_name).property, 'mapper')