如何在flask-sqlalchemy上声明关系

时间:2014-03-27 13:30:43

标签: python sql sqlalchemy flask flask-sqlalchemy

  

我想要链接两个表。

  团队   -id
  -name
  
  活动   -id
  -t1
  -t2
  -date

现在,当我尝试根据日期范围获取所有事件时,如何获取团队名称(t1.name,t2.name),如何创建关系?我是否正确宣布了这段关系?

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'))

1 个答案:

答案 0 :(得分:0)

我似乎找到了解决问题的方法。我现在可以获得每个活动的团队信息。

我取代了这种关系

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

使用以下内容:

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