SQLAlchemy - 将自引用关系映射为一对多(声明形式)

时间:2010-04-14 14:32:22

标签: python sqlalchemy

我想使用声明方法和SQLAlchemy映射Tag实体。标签可以有父(另一个标签)。

我有:

class Tag(Base):
    __tablename__ = 'tag'

    id = Column(Integer, primary_key=True)
    label = Column(String)

    def __init__(self, label, parentTag=None):
        self.label = label

如何添加“父”关系?

4 个答案:

答案 0 :(得分:62)

添加引用父项的ForeignKey,然后创建一个通过remote_side指定方向的关系。这在adjacency list relationships下记录。对于声明,你可以这样做:

class Tag(Base):
    __tablename__ = 'tag'

    id = Column(Integer, primary_key=True)
    label = Column(String)
    parent_id = Column(Integer, ForeignKey('tag.id'))

    parent = relationship('Tag', remote_side=[id])

如果您还想要反向关系,请将backref='children'添加到关系定义中。

答案 1 :(得分:5)

如果您需要孩子,则需要使用uselist

class Tag(Base):
    __tablename__ = 'tag'

    id = Column(Integer, primary_key=True)
    label = Column(String)
    child_id = Column(Integer, ForeignKey('tag.id'))

    children = relation('Tag', remote_side=[id], uselist=True)

答案 2 :(得分:1)

答案 3 :(得分:0)

class Company(BaseModel):
    __tablename__ = 'companies'
    companyName = db.Column(db.String(50))
    contactPerson = db.Column(db.String(50))
    email = db.Column(db.String(50))
    mobile = db.Column(db.String(20))
    parentID = db.Column(db.Integer, db.ForeignKey('companies.id'))  # parent company ID
    childrenCompany = db.relationship('Company', remote_side='Company.id',
                                    backref=db.backref('children_company'))  # parent Company

使用:

In [2]: company_query = Company.query.get_or_404(1)

In [3]: company_query.children_company
Out[3]: 
[<app.models.user.Company at 0x10f527850>,
 <app.models.user.Company at 0x10f527c10>]