确定类是SQLAlchemy关系中的父级还是子级

时间:2015-06-25 21:36:15

标签: python sqlalchemy

给定SQLAlchemy类的关系属性,我想确定它是指父表(外键在另一个表中),还是子表(外键在当前表中) )。

例如,考虑两个类AB,其关系为A.bsB.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函数?

之类的东西

1 个答案:

答案 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.