SQLAlchemy combination

I have a fairly simple model in Flask and SQLAlchemy, with companies playing matches. The match is determined by the host and the guest. I don't know how to bring host and guest companies into the template, I get their IDs.

The code looks 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 a template:

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

      

Any help would be greatly appreciated.

+3


source to share


1 answer


To enable access, you need foreignkey relationship

to sqlalchemy

.

eg,

Decision:

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 a backref

keyword available for reverse access if you need to.

Source

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

+6


source







All Articles