我正在学习一个关于如何使用 Postgres 数据库构建 FastAPI 应用程序的简单 youtube 课程。Users 表具有以下架构(使用 SQLAlchemy):
class User(Base):
"""
Class responsible for the `users` table in the PostgreSQL DB
"""
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True, nullable=False)
email = Column(String, unique=True, nullable=False)
password = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text("now()"))
我注意到,当我尝试使用已使用的邮件创建用户(表中的一行)时,出现错误,这是预期的。然后,如果我将邮件更改为不同的邮件,并再次提交更改,一切都很好......但是,当我检查表中的所有元素时,我看到 id 列跳过了一些值,对应于我得到的那些尝试sqlalchemy.exc.IntegrityError
。
鉴于这种情况,我想知道是否最好先检查一个已经存在的邮件,然后才尝试提交……否则,id 列的值会跳跃。