我想使用声明方法和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
如何添加“父”关系?
答案 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)
parent = relation('Tag')
- 请参阅http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#configuring-relations。
答案 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>]