我有3个表,事件,邀请和提案。我希望能够查询events.invites并返回所有被邀请者的查询(并且能够从我的用户表中获取用户的信息,例如events.invitees.all()[0] .user_name)。同样适用于提案。通过Flask-SQLAlchemy文档阅读,我看到了如何创建多对多表。我一直试图让它们正确配置,但没有运气。这是基于Overholt的Flask-App的一部分。这是我的表格:
events_invitees = db.Table(
'events_invitees',
db.Column('event_id', db.Integer(), db.ForeignKey('events.id')),
db.Column('user_id', db.Integer(), db.ForeignKey('users.id'))
)
events_proposals = db.Table(
'events_proposals',
db.Column('event_id', db.Integer(), db.ForeignKey('events.id')),
db.Column('proposal_id', db.Integer(), db.ForeignKey('proposals.id'))
)
class EventJsonSerializer(JsonSerializer):
pass
class Event(EventJsonSerializer, db.Model):
__tablename__ = 'events'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
event_name = db.Column(db.String(30))
event_mesg = db.Column(db.Text)
start_date = db.Column(db.Date)
end_date = db.Column(db.Date)
event_status = db.Column(db.Boolean)
rsvp = db.Column(db.Date)
created = db.Column(db.DateTime, default=get_current_time)
invitees = db.relationship('Invite',
secondary=events_invitees,
backref=db.backref('events', lazy='dynamic'))
events_proposals = db.relationship('Event',
secondary=events_proposals,
backref=db.backref('events', lazy='dynamic'))
class InviteJsonSerializer(JsonSerializer):
pass
class Invite(InviteJsonSerializer, db.Model):
__tablename__ = 'invites'
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.Date, default=get_current_time)
event_id = db.Column(db.ForeignKey('events.id'))
user_id = db.Column(db.ForeignKey('users.id'))
class ProposalJsonSerializer(JsonSerializer):
pass
class Proposal(ProposalJsonSerializer, db.Model):
__tablename__ = 'proposals'
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.Date, default=get_current_time)
date = db.Column(db.Date)
event_id = db.Column(db.ForeignKey('events.id'))
user_id = db.Column(db.ForeignKey('users.id'))
这是我得到的错误: sqlalchemy.exc.NoForeignKeysError:无法确定关系Event.invitees上父/子表之间的连接条件 - 没有外键通过辅助表'events_invitees'链接这些表。确保引用列与ForeignKey或ForeignKeyConstraint相关联,或指定“primaryjoin”和“secondaryjoin”表达式。
答案 0 :(得分:2)
你可以试试这个:
删除此行event_id = db.Column(db.ForeignKey('events.id'))
并在Invite
表
class Invite(InviteJsonSerializer, db.Model):
__tablename__ = 'invites'
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.Date, default=get_current_time)
user_id = db.Column(db.ForeignKey('users.id'))
从here开始,我们不需要在子表上指定forignkey,因为在父类中使用了'secondary'参数。
并且还将events_invitees“users.id”更改为“invites.id”,如下所示
events_invitees = db.Table(
'events_invitees',
db.Column('event_id', db.Integer(), db.ForeignKey('events.id')),
db.Column('invite_id', db.Integer(), db.ForeignKey('invites.id'))
)