HungryBird
HungryBird

Reputation: 1147

Flask cannot add objects to the session

I am learning the book flask web development, I want to prepare objects to be written to the database (add them to the session), but when I run db.session.add(admin_role), an error occurs. Could anyone help me solve this issue?

This is the code:

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

Inserting Rows

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

Upvotes: 0

Views: 366

Answers (1)

jspcal
jspcal

Reputation: 51894

This line is incorrect because app.config is a dict and setdefault is a function.

track_modifications = app.config.setdefault['SQLALCHEMY_TRACK_MODIFICATIONS']

It should be:

track_modifications = app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', None)

Or even:

track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']

Do you have the latest versions of all your dependencies?

Upvotes: 1

Related Questions