尝试更新值时出现烧瓶SQLAlchemy IntegrityError“唯一约束失败”

时间:2019-06-21 09:10:20

标签: python python-3.x flask flask-sqlalchemy flask-login

我有一个带有用户认证系统的Flask网站。 尝试将更改提交到数据库时出现错误。

class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
surname = db.Column(db.String)
email = db.Column(db.String, unique=True)
password = db.Column(db.String)
registered_on = db.Column(db.DateTime)
admin = db.Column(db.Boolean)
avatar = db.Column(db.String)
confirmed = db.Column(db.Boolean)
confirmed_on = db.Column(db.DateTime)

cloud_storage_actived = db.Column(db.String)

def __init__(self, name=None, surname=None, email=None, password=None, user_id=None, confirmed=None, confirmed_on=None, admin=False, avatar='/static/avatars/default.png', cloud_storage_actived=False):
    self.id = user_id
    self.name = name
    self.surname = surname
    self.email = email
    self.password = password
    self.admin = admin
    self.avatar = avatar
    self.confirmed = confirmed
    self.confirmed_on = confirmed_on
    self.registered_on = datetime.datetime.now()

    self.cloud_storage_actived = cloud_storage_actived

def is_authenticated(self):
    return True
user = User.query.filter_by(email=current_user.email).first_or_404()
user.query.update(dict(name=request.form['name'], 
surname=request.form['surname'], email=request.form['email'], avatar=url_for('static', filename='avatars/') + filename if filename else current_user.avatar))
db.session.commit()
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: user.email
[SQL: UPDATE user SET name=?, surname=?, email=?, avatar=?]
[parameters: ('MyName', 'MySurname', 'MyEmail', '/static/avatars/1.gif')]
(Background on this error at: http://sqlalche.me/e/gkpj)

我在互联网上搜索了如何操作,但没有找到答案。

1 个答案:

答案 0 :(得分:0)

这是因为您将所有用户记录更新为相同的值。您的查询应具有where语句。

您正在运行的查询是

UPDATE user SET name='MyName', surname='MySurname', email='MyEmail', avatar='/static/avatars/1.gif'

但实际上应该是这样的:

UPDATE user SET name='MyName', surname='MySurname', email='MyEmail', avatar='/static/avatars/1.gif' WHERE id = someid

您只应使用where语句更新一个用户:

user = User.query.filter_by(email=current_user.email).first_or_404()
user.query.update(dict(name=request.form['name'], surname=request.form['surname'], email=request.form['email'], avatar=url_for('static', filename='avatars/') + filename if filename else current_user.avatar)).where(User.email == current_user.email)
db.session.commit()

但是因为您使用的是模型,所以您也可以更新模型

user = User.query.filter_by(email=current_user.email).first_or_404()
user.name = request.form['name']
user.surname = request.form['surname']
user.email = request.form['email']
user.avatar = url_for('static', filename='avatars/') + filename if filename else current_user.avatar
db.session.flush()
db.session.commit()