如何使用WTForms和SQLAlchemy更新多对多数据?

时间:2012-03-27 08:17:48

标签: python sqlalchemy flask wtforms flask-sqlalchemy

我在使用Flask Framework进行App构建时遇到了一个小问题。

我正在尝试创建一个简单的User + Permissions模块。要归档它,我在用户和权限表之间存在多对多关系。

这是我的模型,形式和路线

模型

user_perm = db.Table('user_perm',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('perm_id', db.Integer, db.ForeignKey('permissions.id'))
)

class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), unique=True, nullable=False)
    pwdhash = db.Column(db.String(16), nullable=False)
    email = db.Column(db.String(128))
    permissions = db.relationship('Permission', secondary=user_perm, backref=db.backref('users', lazy='dynamic'))

    def __init__(self, username, pwdhash, email, perms):
        self.username = unicode(username)
        self.pwdhash = pwdhash
        self.email = email
        self.permissions = perms

    def __repr__(self):
        return '<User {0}>'.format(self.username)

class Permission(db.Model):
    __tablename__ = 'permissions'
    id = db.Column(db.Integer)
    perm = db.Column(db.String(50), primary_key=True, unique=True, nullable=False)

    def __init__(self, perm):
        self.perm = unicode(perm)

    def __repr__(self):
        return '<Permission {0}>'.format(self.perm)

表格

class AddUser(Form):
    username = TextField(u'Username', required)
    pwdhash = TextField(u'Password', required)
    email = TextField(u'E-email', email_validators)
    permissions = SelectMultipleField(u'Permissions', required, coerce=int)

class EditUser(AddUser):
    pass

路线

@app.route('/admin/user/add', methods=['GET', 'POST'])
@login_required
def admin_user_add():
    form = AddUser(request.form)
    form.permissions.choices = [(p.id, p.perm) for p in Permission.query.order_by('perm')]
    if request.method == 'POST' and form.validate():
        user = User(
            form.username.data,
            form.pwdhash.data,
            form.email.data,
            Permission.query.filter(Permission.id.in_(form.permissions.data)).all()
        )
        db.session.add(user)
        db.session.commit()
        flash('Successfully added user', category='success')
        return redirect(url_for('users'))
    return render_template('admin_user_add.html', form=form)

@app.route('/admin/user/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def admin_user_edit(user_id):
    user = User.query.filter_by(id=user_id).first_or_404()
    form = EditUser(request.form, obj=user)
    form.permissions.choices = [(p.id, p.perm) for p in Permission.query.order_by('perm')]
    form.permissions.data = [p.id for p in user.permissions]
    if request.method == 'POST' and form.validate():
        form.populate_obj(user)
        user.username = form.username.data
        user.pwdhash = form.pwdhash.data
        user.email = form.email.data
        user.permissions = Permission.query.filter(Permission.id.in_(form.permissions.data)).all()
        db.session.merge(user)
        db.session.commit()
        flash('Successfully updated user', category='success')
        return redirect(url_for('users'))
    return render_template('admin_user_add.html', form=form, edit=True)

添加操作完美无缺,关系已添加,但当我尝试编辑用户时,我收到此错误。

回溯

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1518, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1506, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1504, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1264, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1262, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1248, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/var/www/deploy.staging.inovae.ch/webapp/webapp/utilities.py", line 29, in inner
    return f(*args, **kwargs)
  File "/var/www/deploy.staging.inovae.ch/webapp/webapp/utilities.py", line 44, in wrapper
    return f(*args, **kwargs)
  File "/var/www/deploy.staging.inovae.ch/webapp/webapp/views.py", line 161, in admin_user_edit
    form.populate_obj(user)
  File "/usr/local/lib/python2.7/dist-packages/wtforms/form.py", line 73, in populate_obj
    field.populate_obj(obj, name)
  File "/usr/local/lib/python2.7/dist-packages/wtforms/fields/core.py", line 283, in populate_obj
    setattr(obj, name, self.data)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 155, in __set__
    instance_dict(instance), value, None)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 892, in set
    lambda adapter, i: adapter.adapt_like_to_iterable(i))
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 927, in _set_iterable
    collections.bulk_replace(new_values, old_collection, new_collection)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 681, in bulk_replace
    new_adapter.append_with_event(member)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 555, in append_with_event
    getattr(self._data(), '_sa_appender')(item, _sa_initiator=initiator)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 945, in append
    item = __set(self, item, _sa_initiator)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 920, in __set
    item = getattr(executor, 'fire_append_event')(item, _sa_initiator)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 614, in fire_append_event
    item, initiator)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 800, in fire_append_event
    value = fn(state, value, initiator or self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 35, in append
    item_state = attributes.instance_state(item)
AttributeError: 'long' object has no attribute '_sa_instance_state'

2 个答案:

答案 0 :(得分:11)

问题的原因

问题的关键在于 SQL Alchemy期望permissions关系填充sqlalchemy permission对象,而不是你传递的int
 在您看来:

form = EditUser(request.form, obj=user)
form.permissions.choices = [(p.id, p.perm) for p in Permission.query.order_by('perm')]
form.permissions.data = [p.id for p in user.permissions]

因此,在您的表单中,form.permissions实际上只是持有权限对象的id(int),而不是对象本身。当您致电form.populate_obj(user)时,当它到达权限段时,它将调用此方法:

setattr(obj, name, self.data)

转换为:

setattr(user, permissions, sefl.data)

转换为:

user.permissions = [1, 3, 4 ...]

但是SQL Alchemy希望:

user.permissions = [sqlalchemyobject1, sqlalchemyobject2, ...]

解决方案

至少有几种方法可以解决这个问题。我使用的方法是sqlalchemy的Association Proxy。这将允许您执行诸如将整数列表传递到用户模型之类的操作,以及让模型将它们转换为权限对象

class User(db.Model):
    ...
    permissions_relationship = ('Permission', cascade="all,delete,delete-orphan")
    permissions = association_proxy('permissions_relationship', 'perm',
                            creator=lambda perm: Permission(perm=perm)

class Permission(db.Model):  
    ...
    perm = ...

    def __init__(self,perm):  
        self.perm = perm

在一个Nutshell中,association_proxy调用简单地说:“当你传递一个项目列表(Ints,Strings,无论如何)时,通过这样做将它们转换为Permission个对象:{{1在上面的代码中使用此解决方案,您将删除行Permission(perm=perm)

最后,form.permissions.data = [p.id for p in user.permissions]还提供QuerySelectMultiple field。我没有使用它,但想象它也可以解决这个问题。

答案 1 :(得分:0)

不应form.permissions.data = [p.id for p in user.permissions]form.permissions.data = list(user.permissions)(错误表明SQLAlchemy找到了一个长对象,其中需要一个ORM映射类的实例。)