给定SQLAlchemy类的关系属性,我想确定它是指父表(外键在另一个表中),还是子表(外键在当前表中) )。
例如,考虑两个类A
和B
,其关系为A.bs
和B.a
:
class B(Base):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('a.id'))
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
bs = relationship(B, backref='a')
在A.bs
关系中,A是"父母"因为外键是在另一个类中。在B.a
关系中,B是"孩子"因为外键在同一个类中。如果我有一个函数is_parent
,它就会这样做:
is_parent(A.bs) == True
is_parent(B.a) == False
如何使用SQLAlchemy实现is_parent
函数?
答案 0 :(得分:0)
(Honestly, I can't quite imagine why you would want this, but it is more or less easy to solve looking at the structure of the class).
In [37]:
from sqlalchemy.orm.properties import ColumnProperty
from sqlalchemy.orm.relationships import RelationshipProperty
def is_parent(obj):
if type(obj.property) == ColumnProperty:
return False
if type(obj.property) == RelationshipProperty:
return True
return None
print is_parent(B.a_id)
print is_parent(A.bs)
False
True
Hope it helps.