【问题标题】:SQLAlchemy: __init__() takes 1 positional argument but 2 were given (many to many)SQLAlchemy:__init__() 接受 1 个位置参数,但给出了 2 个(多对多)
【发布时间】: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


【解决方案1】:

append 的调用正在尝试对create a new instanceMatchTeams,从文档中可以看出。这也在您链接到的“简化关联对象”下注明:

其中,每个.keywords.append() 操作相当于:

&gt;&gt;&gt; user.user_keywords.append(UserKeyword(Keyword('its_heavy')))

因此你的

find_match.teams.append(find_liverpool)

等价于

find_match.match_teams.append(MatchTeams(find_liverpool))

由于MatchTeams 没有明确定义__init__,它使用_default_constructor() 作为constructor(除非你已经覆盖它),除了self,它只接受关键字参数,唯一的位置参数.

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

class Match(db.Model):

    teams = association_proxy('match_teams', 'team',
                              creator=lambda team: MatchTeams(team=team))

或在MatchTeams 上定义__init__ 以满足您的需求,例如:

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.

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2017-04-22
    • 2017-11-23
    • 2022-01-04
    • 2019-10-27
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多