简体   繁体   中英

How do I do declare relationship on flask-sqlalchemy

I have two tables I want to link.

Teams
-id
-name

Event
-id
-t1
-t2
-date

Now how do I create a relationship if I want to get team name (t1.name, t2.name) when I try to get all the events based on date range? Did I declare the relationship correctly?

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from app import app, db

class Team(db.Model):
    __tablename__ = 'teams'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String)
    teams_event = relationship('Team', secondary=Event.__tablename__, primaryjoin=id == Event.t1, secondaryjoin=id == Event.t2, lazy='dynamic')

class Event(db.Model):
    __tablename__ = 'events'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    t1 = db.Column(db.Integer, ForeignKey('Team.id'))
    t2 = db.Column(db.Integer, ForeignKey('Team.id'))

It seems I found a solution to my problem. I can now get the team information for every event.

I replaced this relationship

teams_event = relationship('Team', secondary=Event.__tablename__, primaryjoin=id == Event.t1, secondaryjoin=id == Event.t2, lazy='dynamic')

With the following:

t1_teams = relationship('Team', primaryjoin=('Event.t1 == Team.id'))
t2_teams = relationship('Team', primaryjoin=('Event.t2 == Team.id'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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