zer*_*dge 5 python sqlite sqlalchemy flask-sqlalchemy
SQLAlchemy无疑是非常强大的,但是文档隐含地假定了许多先验知识和关系的主题,混合backref了新优选的back_populates()方法,我觉得很困惑.
以下模型设计几乎是文档中指南的精确镜像,该文档处理多对多关系的关联对象.您可以看到评论仍然与原始文章中的评论相同,我只更改了实际代码.
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)
Run Code Online (Sandbox Code Playgroud)
但是这个应该将团队实例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)
Run Code Online (Sandbox Code Playgroud)
并输出以下内容:
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'>
Run Code Online (Sandbox Code Playgroud)
Ilj*_*ilä 17
调用append试图创建一个新的实例中MatchTeams,从文件中可以看出.您在链接到的"简化关联对象"中也会注明到这一点:
如上所述,每项
.keywords.append()操作相当于:
>>> user.user_keywords.append(UserKeyword(Keyword('its_heavy')))
因此你的
find_match.teams.append(find_liverpool)
Run Code Online (Sandbox Code Playgroud)
相当于
find_match.match_teams.append(MatchTeams(find_liverpool))
Run Code Online (Sandbox Code Playgroud)
由于MatchTeams没有明确定义__init__,它使用_default_constructor()as 构造函数(除非你重写它),它除了只接受关键字参数self,唯一的位置参数.
要解决此问题creator,请将工厂传递给您的关联代理:
class Match(db.Model):
teams = association_proxy('match_teams', 'team',
creator=lambda team: MatchTeams(team=team))
Run Code Online (Sandbox Code Playgroud)
或定义__init__上MatchTeams,以满足您的需求,例如:
class MatchTeams(db.Model):
# Accepts as positional arguments as well
def __init__(self, team=None, match=None):
self.team = team
self.match = match
Run Code Online (Sandbox Code Playgroud)
或显式创建关联对象:
db.session.add(MatchTeams(match=find_match, team=find_liverpool))
# etc.
Run Code Online (Sandbox Code Playgroud)