SQLAlchemy: __init__() takes 1 positional argument but 2 were given (many to many)

左心房为你撑大大i 提交于 2019-12-05 11:40:27

The call to append is trying to create a new instance of MatchTeams, as can be seen from the documentation. This is also noted under "Simplifying Association Objects" that you linked to:

Where above, each .keywords.append() operation is equivalent to:

>>> user.user_keywords.append(UserKeyword(Keyword('its_heavy')))

Hence your

find_match.teams.append(find_liverpool)

is equivalent to

find_match.match_teams.append(MatchTeams(find_liverpool))

Since MatchTeams has no explicitly defined __init__, it's using the _default_constructor() as constructor (unless you've overridden it), which accepts only keyword arguments in addition to self, the only positional argument.

To remedy this either pass a creator factory to your association proxy:

class Match(db.Model):

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

or define __init__ on MatchTeams to suit your needs, for example:

class MatchTeams(db.Model):

    # Accepts as positional arguments as well
    def __init__(self, team=None, match=None):
        self.team = team
        self.match = match

or create the association object explicitly:

db.session.add(MatchTeams(match=find_match, team=find_liverpool))
# etc.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!