UNIQUE 约束失败(SQLAlchemy)

Posted

技术标签:

【中文标题】UNIQUE 约束失败(SQLAlchemy)【英文标题】:UNIQUE constraint failed (SQLAlchemy) 【发布时间】:2021-12-09 21:52:28 【问题描述】:

当我使用 db.commit.session() 时,我的烧瓶应用程序抛出错误。我看不出我的代码中的错误在哪里。这是终端中的代码和错误:

>>> user_1 = User(username='Corey', email='C@demo.com', password='password')
>>> db.session.add(user_1)
>>> user_2 = User(username='JohnDoe', email='jd@demo.com', password='password')
>>> db.session.add(user_2)
>>> db.create_all()
>>> db.session.commit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in commit
  File "C:\Users\hp\miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:\Users\hp\miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 827, in commit
    self._assert_active(prepared_ok=True)
  File "C:\Users\hp\miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 608, in _assert_active
    code="7s2a",
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.image_file
[SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('JohnDoe', 'jd@demo.com', 'default.jpg', 'password')]
(Background on this error at: https://sqlalche.me/e/14/gkpj) (Background on this error at: https://sqlalche.me/e/14/7s2a)

老实说,我不知道这是我的终端代码还是我的主代码。

这是我的应用程序中的代码:

from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm, LoginForm
 
app = Flask(__name__)
app.config['SECRET_KEY'] = 'cac78a5498388aa4a95fb2be0f0a6499'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), unique=True, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref="author", lazy=True)

    def __repr__(self):
        return f"User('self.username','self.email','self.image_file')"

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('self.title','self.date_posted')"

【问题讨论】:

UNIQUE constraint failed: user.image_file。猜测您已经有一行将image_file 设置为'default.jpg'。也许值得看看我写的关于avoiding duplicate filenames for Flask uploads的另一个答案 【参考方案1】:

问题是您在指定unique=True 时将用户模型的列image_file 定义为“唯一”。然后,当您创建新用户(未指定 image_file)时,这会引发错误,因为默认的 image_file 始终是“default.jpg”。基本上,您只需要删除image_file 列中的unique=True 属性,因为新用户(默认情况下)将拥有相同的图像文件。

【讨论】:

以上是关于UNIQUE 约束失败(SQLAlchemy)的主要内容,如果未能解决你的问题,请参考以下文章

Flask 学习-83.Flask-SQLAlchemy 联合唯一约束

IOS Coredata UNIQUE 约束失败:

SQLError 19 UNIQUE 约束失败

模型 unique_together 约束 + 无 = 失败?

UNIQUE 约束失败:ZTEMPORADA.Z_PK

Flask SQLAlchemy NOT NULL 约束在主键上失败