简体   繁体   English

Flask SQLAlchemy关系

[英]Flask SQLAlchemy relationship

I have a pretty simple model in Flask and SQLAlchemy, with companies playing matches. 我在Flask和SQLAlchemy中有一个非常简单的模型,公司在玩火柴。 A match is defined by a host and a guest. 匹配由主机和来宾定义。 I don't know how to bring the host and the guest companies to the template, I am getting their IDs. 我不知道如何将主机和访客公司带到模板,我正在获取他们的ID。

The code is like this: 代码是这样的:

class Company(db.Model):

    __tablename__ = 'companies'
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(64), unique = True)
    address = db.Column(db.String(120), unique = False)
    website = db.Column(db.String(100), unique = False)
    ...

class Match(db.Model):

    __tablename__ = 'matches'
    id = db.Column(db.Integer, primary_key = True)

    local_id =db.Column(db.Integer, db.ForeignKey('companies.id'))    
    guest_id = db.Column(db.Integer, db.ForeignKey('companies.id'))

    match_time = db.Column(db.DateTime())   # not important

I would like to be able to do something like this in the template: 我希望能够在模板中执行以下操作:

{{ match.host.name }} - {{ match.guest.name }}

Any help would be greatly appreciated. 任何帮助将不胜感激。

You need to have foreignkey relationship in sqlalchemy to enable the access. 你需要有foreignkey relationshipsqlalchemy启用访问。

for example, 例如,

Solution: 解:

class Match(db.Model):
    __tablename__ = 'matches'

    id = db.Column(db.Integer, primary_key = True)

    local_id =db.Column(db.Integer, db.ForeignKey('companies.id'))    
    guest_id = db.Column(db.Integer, db.ForeignKey('companies.id'))

    local = db.relationship('Company', foreign_keys=local_id)
    guest = db.relationship('Company', foreign_keys=guest_id)

    match_time = db.Column(db.DateTime())   # not important

This will solve your problem.There is even backref keyword available to do reverse access if you need. 这将解决您的问题。如果您需要,甚至可以使用backref关键字进行反向访问。

source 资源

http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM