如何在 SQLAlchemy 中使用关系
我是 SQLAlchemy
的新手,在将关系概念实现到我的逻辑中时遇到了困难。
我有两个表:Offices
和 Departments
,其中部门包括其所在的办公室。
我尝试应用文档 https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_building_relationship.htm 但我很难理解应该在哪里插入 Relationship
以及是否 back_populates
属性在这种情况下实际上很有用。
class Offices(Base):
__tablename__: 'offices'
id = Column(Integer, primary_key=True)
name = Column(String)
code = Column(String)
reader = Column(Integer)
class Departments(Base):
__tablename__ = 'departments'
id = Column(Integer, primary_key=True)
name = Column(String)
office_id = Column(Integer, ForeignKey('offices.id'))
office = relationship("Offices", back_populates="departments")
def __init__(self, name):
self.name = name
另外,我是否必须在 department
的 __init__
中定义与 office
相关的任何内容,以便在尝试插入新行时保存它到表中?
I am new to SQLAlchemy
and I am having troubles implementing the concept of relationships into my logic.
I have two tables: Offices
and Departments
where departments include the office it exists in.
I tried to apply the information present in the documentation https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_building_relationship.htm but I am having struggles understanding where should I insert the Relationship
and if back_populates
attribute is actually useful in this case.
class Offices(Base):
__tablename__: 'offices'
id = Column(Integer, primary_key=True)
name = Column(String)
code = Column(String)
reader = Column(Integer)
class Departments(Base):
__tablename__ = 'departments'
id = Column(Integer, primary_key=True)
name = Column(String)
office_id = Column(Integer, ForeignKey('offices.id'))
office = relationship("Offices", back_populates="departments")
def __init__(self, name):
self.name = name
Also, will I have to define anything related to the office
in the department
's __init__
in order to save it when I try inserting new rows into the table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在两个模型中指定它们
relationship
之后您可以实现此目的(假设
department
和office
是对象)替代方案是
backref
。它会自己创建反向关系,所以会做与第一个相同的事情
You can specify them
relationship
in both modelsAfter that you can achieve this (assume
department
andoffice
are objects)The alternative is
backref
. It will create reverse relationship by itself, sowill do the same the first does