我正在学习书籍web开发,我想准备要写入数据库的对象(将它们添加到会话中),但是当我运行db.session.add(admin_role)
时,会发生错误。有谁能帮我解决这个问题?
这是代码:
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
插入行
>>> from hello import Role, User
>>> admin_role = Role(name='Admin')
>>> mod_role = Role(name='Moderator')
>>> user_role = Role(name='User')
>>> user_john = User(username='john', role=admin_role)
>>> user_susan = User(username='susan', role=user_role)
>>> user_david = User(username='david', role=user_role)
>>> db.session.add(admin_role)
Traceback (most recent call last):
File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 999, in __call__
return self.registry[key]
KeyError: 4321375104
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 153, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 1001, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2950, in __call__
return self.class_(**local_kw)
File "/Users/cool/PycharmProjects/website/venv/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 142, in __init__
track_modifications = app.config.setdefault['SQLALCHEMY_TRACK_MODIFICATIONS']
TypeError: 'builtin_function_or_method' object is not subscriptable
答案 0 :(得分:1)
这一行不正确,因为app.config
是一个字典,setdefault
是一个函数。
track_modifications = app.config.setdefault['SQLALCHEMY_TRACK_MODIFICATIONS']
应该是:
track_modifications = app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', None)
甚至:
track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
您是否拥有所有依赖项的最新版本?