首先,数据库概述:
competitors
- 参与竞争的人competitions
- 人们竞争的事情competition_registrations
- 参加特定比赛的参赛者event
- 比赛中的“赛事”。events_couples
- 一对(2名参赛者)参加比赛。首先,EventCouple
是一个与events_couples
对应的Python类,它是:
class EventCouple(Base):
__tablename__ = 'events_couples'
competition_id = Column(Integer, ForeignKey('competitions.id'), primary_key=True)
event_id = Column(Integer, ForeignKey('events.id'), primary_key=True)
leader_id = Column(Integer)
follower_id = Column(Integer)
__table_args__ = (
ForeignKeyConstraint(['competition_id', 'leader_id'], ['competition_registrations.competition_id', 'competition_registrations.competitor_id']),
ForeignKeyConstraint(['competition_id', 'follower_id'], ['competition_registrations.competition_id', 'competition_registrations.competitor_id']),
{}
)
我有一个Python类CompetitorRegistration
,它对应于competition_registrations
中的记录/行。注册的竞争者可以参加多项赛事,但要么是“领导者”,要么是“追随者”。我想将CompetitorRegistration
添加到leading
属性EventCouple
,这是competition_id
和leader_id
匹配的CompetitorRegistration
列表。这是我的class CompetitorRegistration(Base):
__tablename__ = 'competition_registrations'
competition_id = Column(Integer, ForeignKey('competitions.id'), primary_key=True)
competitor_id = Column(Integer, ForeignKey('competitors.id'), primary_key=True)
email = Column(String(255))
affiliation_id = Column(Integer, ForeignKey('affiliation.id'))
is_student = Column(Boolean)
registered_time = Column(DateTime)
leader_number = Column(Integer)
leading = relationship('EventCouple', primaryjoin=and_('CompetitorRegistration.competition_id == EventCouple.competition_id', 'CompetitorRegistration.competitor_id == EventCouple.leader_id'))
following = relationship('EventCouple', primaryjoin='CompetitorRegistration.competition_id == EventCouple.competition_id and CompetitorRegistration.competitor_id == EventCouple.follower_id')
课程,完成了尝试:
ArgumentError: Could not determine relationship direction for primaryjoin
condition 'CompetitorRegistration.competition_id == EventCouple.competition_id
AND CompetitorRegistration.competitor_id == EventCouple.leader_id', on
relationship CompetitorRegistration.leading. Ensure that the referencing Column
objects have a ForeignKey present, or are otherwise part of a
ForeignKeyConstraint on their parent Table, or specify the foreign_keys parameter
to this relationship.
但是,我得到了:
following
感谢您的帮助,&如果模式需要更多信息,请告诉我。
另外,我的另一次尝试在competition_id
中可见 - 这没有错误,但也没有给出正确的结果。 (它只加入follower_id
,完全忽略了{{1}})
答案 0 :(得分:0)
您的leading
条件会将表达式和字符串混合为eval()
。并且following
的条件混合了Python和SQL运算符:Python中的and
不是您所期望的。以下是使用两种变体的更正示例:
leading = relationship('EventCouple', primaryjoin=(
(competition_id==EventCouple.competition_id) & \
(competitor_id==EventCouple.leader_id)))
leading = relationship('EventCouple', primaryjoin=and_(
competition_id==EventCouple.competition_id,
competitor_id==EventCouple.leader_id))
following = relationship('EventCouple', primaryjoin=\
'(CompetitorRegistration.competition_id==EventCouple.competition_id) '\
'& (CompetitorRegistration.competitor_id==EventCouple.follower_id)')