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
由于您有两个classprofile
和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')