【发布时间】:2016-12-19 12:17:13
【问题描述】:
SQLAlchemy 无疑是非常强大的,但文档隐含地假设了很多先验知识和关于关系的主题,混合了 backref 和新近首选的 back_populates() 方法,我觉得这很令人困惑。
以下模型设计与处理Association Objects for many-to-many relationships 的文档中的指南几乎完全一致。可以看到cmet还是和原文章一样,我只是改了实际的代码。
class MatchTeams(db.Model):
match_id = db.Column(db.String, db.ForeignKey('match.id'), primary_key=True)
team_id = db.Column(db.String, db.ForeignKey('team.id'), primary_key=True)
team_score = db.Column(db.Integer, nullable="True")
# bidirectional attribute/collection of "user"/"user_keywords"
match = db.relationship("Match",
backref=db.backref("match_teams",
cascade="all, delete-orphan")
)
# reference to the "Keyword" object
team = db.relationship("Team")
class Match(db.Model):
id = db.Column(db.String, primary_key=True)
# Many side of many to one with Round
round_id = db.Column(db.Integer, ForeignKey('round.id'))
round = db.relationship("Round", back_populates="matches")
# Start of M2M
# association proxy of "match_teams" collection
# to "team" attribute
teams = association_proxy('match_teams', 'team')
def __repr__(self):
return '<Match: %r>' % (self.id)
class Team(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
goals_for = db.Column(db.Integer)
goals_against = db.Column(db.Integer)
wins = db.Column(db.Integer)
losses = db.Column(db.Integer)
points = db.Column(db.Integer)
matches_played = db.Column(db.Integer)
def __repr__(self):
return '<Team %r with ID: %r>' % (self.name, self.id)
但是这个 sn-p,它应该将团队实例 find_liverpool 与匹配实例 find_match(两个样板对象)相关联,不起作用:
find_liverpool = Team.query.filter(Team.id==1).first()
print(find_liverpool)
find_match = Match.query.filter(Match.id=="123").first()
print(find_match)
find_match.teams.append(find_liverpool)
并输出以下内容:
Traceback (most recent call last):
File "/REDACT/temp.py", line 12, in <module>
find_match.teams.append(find_liverpool)
File "/REDACT/lib/python3.4/site-packages/sqlalchemy/ext/associationproxy.py", line 609, in append
item = self._create(value)
File "/REDACT/lib/python3.4/site-packages/sqlalchemy/ext/associationproxy.py", line 532, in _create
return self.creator(value)
TypeError: __init__() takes 1 positional argument but 2 were given
<Team 'Liverpool' with ID: 1>
<Match: '123'>
【问题讨论】:
-
您需要提供更多信息。是什么产生了这个错误?它不可能是您发布的 sn-p,因为如果第一行引发错误,则不会填充
find_liverpool,但它显然是。请显示完整的代码和回溯。 -
@DanielRoseman 我发布的代码是导致错误的原因。我添加了完整的回溯。 find_liverpool 在
TypeError之前填充,但由于某种原因,打印输出在它之后。
标签: python sqlite sqlalchemy flask-sqlalchemy