小编ask*_*boe的帖子

在SQLAlchemy中,如何在具有多个关系时访问查询中的引用属性?

数据库结构

我有两个类,A和B,它们有两种不同的关系:

1)使用关联表(关联)来存储仅与该特定关联相关的信息(association_property_1)并通过A和B中的backref实例化的多对多关系.

2)使用table_b中的外键,A和B之间的一对一关系,这样只有B'知道'这种关系.我不在乎A是否知道它,但这样看起来似乎更简单.

我的课程看起来像这样:

class A(Base):
  __tablename__ = 'table_a'

  id = Column(Integer, primary_key=True)
  a_property_1 = Column(Float)
  a_property_2 = Column(Float)
  a_property_special = Column(Float)

  # Many-to-many relationship with B through an Association
  associated_bs = relationship('Association', backref='a')

class B(Base):
  __tablename__ = 'table_b'

  id = Column(Integer, primary_key=True)
  b_property_1 = Column(Float)
  b_property_2 = Column(Float)

  # One-to-one relationship with A
  a_id = Column(Integer, ForeignKey('table_a.id'))
  a = relationship('A', uselist=False, backref='b')

  # Many-to-many relationship with A through an Association
  associated_as = relationship('Association', backref='b')

class Association(Base):
  __tablename__ = …
Run Code Online (Sandbox Code Playgroud)

python sql database orm sqlalchemy

2
推荐指数
1
解决办法
3014
查看次数

标签 统计

database ×1

orm ×1

python ×1

sql ×1

sqlalchemy ×1