我正在使用flask-sqlalchemy实现多对多关系。尝试了许多选项,但无法查询所有孩子的父母。
<div class="gallery">
<div class="article">
<div class="grid left">
<a class="inset-contents top img"></a>
<div class="inset-contents bottom">
<a class="inner-contents first img"></a>
<a class="inner-contents second img"></a>
</div>
</div>
<a class="grid right img"></a>
</div>
</div>
在此多对多关系示例中,我将如何查询参与者参加的所有比赛?
我尝试了以下操作:
class Participant(db.Model):
__tablename__='participant'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(120), unique=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship("User")
@staticmethod
def get_by_user(user):
return Participant.query.filter_by(user=user).first()
def __repr__(self):
return "(Participant '{}')".format(self.email)
competitions = db.relationship("CompetitionParticipant", back_populates="participant")
class Competition(db.Model):
__tablename__='competition'
__table_args__={'extend_existing':True}
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(100),unique=True)
description=db.Column(db.String(255),unique=True)
# type=db.Column(db.String(50))#Team,Individual,Practice,etc.
start_date=db.Column(db.DateTime)
end_date=db.Column(db.DateTime)
result_date=db.Column(db.DateTime)
participants = db.relationship('CompetitionParticipant', back_populates='competition')
def __repr__(self):
return "(Competition '{}')".format(self.name)
class CompetitionParticipant(db.Model):
__tablename__='competition_participant'
__table_args__={'extend_existing':True}
id=db.Column(db.Integer,primary_key=True)
participant_id=db.Column(db.Integer, db.ForeignKey('participant.id'))
competition_id=db.Column(db.Integer, db.ForeignKey('competition.id'))
competition=db.relationship("Competition",back_populates="participants")
participant=db.relationship("Participant",back_populates="competitions")
def __repr__(self):
return "(competition_id, participant_id '{},{}')".format(self.competition_id,self.participant_id)
我尝试的所有其他操作都是语法错误。提取参与者参加的所有比赛的正确ORM方法是什么?
答案 0 :(得分:1)
例如,如果您想获取特定用户的比赛数据:
participants = Participant.query.filter_by(id=1).all()
您可以遍历参与者并获取数据:
for participant in participants:
for competition in participant.competitions:
print(competition.competition.name)
答案 1 :(得分:0)
如果您想了解有关id = 1的参与者的信息,您应该不能做这样的事情:
participant = Participant.query.get(1)
for item in participant.competitions:
print(item.name)