SQLAlchemy:__ init __()需要1个位置参数,但是给出了2个(多对多)

时间:2016-12-19 12:17:13

标签: python sqlite sqlalchemy flask-sqlalchemy

SQLAlchemy无疑是非常强大的,但是文档隐含地假定了许多先验知识和关系主题,backref和新首选back_populates()方法之间的混合,我觉得很困惑

以下模型设计几乎是处理Association Objects for many-to-many relationships的文档中指南的精确镜像。您可以看到评论仍然与原始文章中的评论相同,而且我只更改了实际代码。

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)

但是这个应该将团队实例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'>

1 个答案:

答案 0 :(得分:13)

append的调用正在尝试MatchTeams .keywords.append(),正如文档中所示。这也在您链接到的“简化关联对象”中注明:

  

在上述情况下,每个>>> user.user_keywords.append(UserKeyword(Keyword('its_heavy')))操作等同于:

     

find_match.teams.append(find_liverpool)

因此你的

find_match.match_teams.append(MatchTeams(find_liverpool))

相当于

MatchTeams

由于__init__没有明确定义self,因此它使用create a new instance作为_default_constructor()(除非您已覆盖它),除了它之外只接受关键字参数class Match(db.Model): teams = association_proxy('match_teams', 'team', creator=lambda team: MatchTeams(team=team)) ,唯一的位置论证。

要解决此问题,请将constructor工厂传递给您的关联代理:

__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 以满足您的需求,例如:

db.session.add(MatchTeams(match=find_match, team=find_liverpool))
# etc.

或明确创建关联对象:

public function hasOneRelation($model)
{
    return $this->hasOne($model);
}