【问题标题】:Flask-SQLAlchemy - TypeError: __init__() takes only 1 positionFlask-SQLAlchemy - TypeError: __init__() 只占 1 个位置
【发布时间】:2026-01-06 04:25:02
【问题描述】:

我只想用 flask-sqlalchemy 创建和测试数据库。数据库创建成功。我的代码:

class Entry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    occurences = db.Column(db.String(80), unique=True)

a = Entry('run.py:27')

错误:

    a = Entry('run.py:27')
TypeError: __init__() takes 1 positional argument but 2 were given

如果我尝试在没有参数的情况下执行此操作,程序将返回:

qlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table:        entry [SQL: 'INSERT INTO entry (occurences) VALUES (?)'] [parameters: (None,)]

错误开始于

db.session.commit()

【问题讨论】:

    标签: python flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    根据他们的docs

    SQLAlchemy 为所有模型类添加了一个隐式构造函数,它接受所有列和关系的关键字参数。如果您出于任何原因决定重写构造函数,请确保继续接受 **kwargs 并使用这些 **kwargs 调用超级构造函数以保留此行为...

    意味着您的代码失败,因为构造函数需要关键字参数。 您可以通过以下方式修复它:

    # instantiating Entry with the occurences keyword
    a = Entry(occurences='run.py:27')
    

    或覆盖__init__...在这种情况下,您还应该包含**kwargs 和对super 的调用。

    【讨论】:

      【解决方案2】:

      您必须定义__init__ 方法以支持模型字段:

      class Entry(db.Model):
          id = db.Column(db.Integer, primary_key=True)
          occurences = db.Column(db.String(80), unique=True)
      
          def __init__(self, occurences):
              self.occurences = occurences
      

      【讨论】: