flask-sqlalchemy:连接表和一个结果对象

时间:2017-11-03 19:05:56

标签: python sqlalchemy

我来自一个python-django,我正试图掌握烧瓶 - SQLAlchemy:

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(128), nullable=False)


class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(128), nullable=False)
    author = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False)

我想获得一个联合结果列表:

results = Book.query.filter(Author.name=='tom')

for result in results:
  print(result.title, result.???.name)

如何访问已连接表格的字段?

1 个答案:

答案 0 :(得分:0)

我明白了:

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(128), nullable=False)
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False)
    author = relationship("Author")

我需要添加一行

author = relationship("Author")

到模特。似乎有必要在对象级别声明关系。我确实想念这个。

现在该行可以是:

print(result.title, result.author.name)