python - SQLAlchemy:__init__() 采用 1 个位置参数,但给出了 2 个(多对多)

标签 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'>

最佳答案

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

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

>>> 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.

关于python - SQLAlchemy:__init__() 采用 1 个位置参数,但给出了 2 个(多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41222412/

相关文章:

python - 安装编译器后重新安装带有加速的 SQLAlchemy

python - Azure-blob-存储。使用 SAS token 访问容器

Python 的属性装饰器没有按预期工作

java - android中识别第二次点击事件

c++ - 负责从sqlite3_column_text中释放指针的sqlite c/c++ api

python - sqlalchemy操作错误: (OperationalError) unable to open database file None None

python - 计算 sigmoid 最快的方法是什么?

python - python中可以直接传字典实例化另一个对象吗

sql - 如果存在 ... SQLite 中的 else 子句

python - SQLAlchemy 2.0 NotImplementedError : engine. 执行