我只想用flask-sqlalchemy创建和测试数据库。 DB创造了成功。我的代码:
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()
答案 0 :(得分:4)
根据他们的docs:
SQLAlchemy为所有模型类添加了一个隐式构造函数,它接受所有列和关系的关键字参数。如果您因任何原因决定覆盖构造函数,请确保继续接受** kwargs并使用这些** kwargs调用超级构造函数以保留此行为...
意味着您的代码失败,因为构造函数需要关键字参数。 您可以通过以下方式修复它:
# instantiating Entry with the occurences keyword
a = Entry(occurences='run.py:27')
或覆盖__init__
...在这种情况下,您还应该包含**kwargs
和超级电话。
答案 1 :(得分: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