我有以下脚本来更新我正在构建的烧瓶Web应用程序的数据库,以自学SQLAlchemy。
from FeedReader import api
from FeedReader import db_session
from FeedReader.models import Article
# Get values for a single record
res = api.get_one().__next__()
# Create the record to be added
article = Article(**res)
# Does this show that the datatypes for `article` match the datatypes in the schema?
for key, val in res.items():
print(key, type(val), type(article.__getattribute__(key)))
# Attempt to add the record, and get an IntegrityError
db_session.add(article)
db_session.commit()
首先运行脚本会打印以下输出:
source <class 'str'> <class 'str'>
id <class 'str'> <class 'str'>
link_url <class 'str'> <class 'str'>
author <class 'str'> <class 'str'>
content <class 'str'> <class 'str'>
publish_date <class 'datetime.date'> <class 'datetime.date'>
source_date <class 'datetime.date'> <class 'datetime.date'>
family <class 'str'> <class 'str'>
title <class 'str'> <class 'str'>
这些数据类型与我宣布我的Article
模型的方式相符:
class Article(Base):
__tablename__ = "Articles"
id = Column(Text, primary_key=True)
read_flag = Column(Boolean, default=False)
link_url = Column(Text)
source = Column(Text)
family = Column(Text)
title = Column(Text)
publish_date = Column(Date)
source_date = Column(Date)
author = Column(Text)
content = Column(Text)
但是对db_session.commit()
的调用会产生以下IntegrityError
IntegrityError: (sqlite3.IntegrityError) datatype mismatch [SQL: 'INSERT INTO "Articles" (id, read_flag, link_url, source, family, title, publish_date, source_date, author, content) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'] ...
我是否误解了IntegrityError的原因?为什么我能够创建一个具有不正确的模式数据类型的Article
对象?