SQLAlchemy 只连接一列

SQLAlchemy join only one column

我定义了以下模型:

class Attribute(Base):
    __tablename__ = "attributes"

    id = Column(BigInteger, primary_key=True, index=True)
    data_id = Column(BigInteger, ForeignKey("data.art_no"))
    name = Column(VARCHAR(500), index=True)

    data = relationship("Data", back_populates="attributes")


class Data(Base):
    __tablename__ = "data"

    art_no = Column(BigInteger, primary_key=True, index=True)
    multiplier = Column(Float)

    attributes = relationship("Attribute", back_populates="data", cascade="all, delete, delete-orphan")

如果我查询一个 Data 对象,我得到这个属性:

[<app.db.models.Attribute object at 0x10d755d30>]

但我想得到:

['attribute name X']

我想要得到的是,属性字段应该是 join 属性的 Attribute.name 字段的数组。

我当前的查询是:

db.query(models.Data).all()

我需要如何修改我的查询,使 Dataattributes 字段不包含 Attribute 对象而仅包含 `Attributes 的字符串 name

希望你能很好地理解这个问题;)

db.query(models.Data).all() returns Data 个对象的数组。因此,您可以在 Data class 上定义自定义 属性 以从属性关系中提取名称:

class Attribute(Base):
    __tablename__ = "attributes"

    id = Column(BigInteger, primary_key=True, index=True)
    data_id = Column(BigInteger, ForeignKey("data.art_no"))
    name = Column(VARCHAR(500), index=True)

    data = relationship("Data", back_populates="attributes_rel")


class Data(Base):
    __tablename__ = "data"

    art_no = Column(BigInteger, primary_key=True, index=True)
    multiplier = Column(Float)

    attributes_rel = relationship("Attribute", back_populates="data", cascade="all, delete, delete-orphan")
    
    @property
    def attributes(self):
        return [attribute.name for attribute in self.attributes_rel]

请注意,默认情况下,sqlalchemy 将在访问时分别为每个 Data 对象获取 attributes_rel。这可能会导致 N+1 选择问题。为避免这种情况,您应该指定 relationship loading technique

也看看with_entities and hybrid attributes