Python SQLAlchemy只连接一列

Python SQLAlchemy只连接一列,python,mysql,sqlalchemy,Python,Mysql,Sqlalchemy,我定义了以下模型: 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)

我定义了以下模型:

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")
如果我查询
数据
对象,我会得到以下属性:

[<app.db.models.Attribute object at 0x10d755d30>]
我想得到的是,attributes字段应该是
连接属性的
Attribute.name
字段的数组

我目前的查询是:

db.query(models.Data).all()
我需要如何修改查询,以便
数据的
属性
字段不包含
属性
对象,而只包含属性的字符串
名称

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

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

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将在访问时分别为每个
数据
对象获取
属性。这可能会导致N+1选择问题。为了避免这种情况,您应该指定

还可以看看和

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]