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]