文章内容

2018/7/10 10:16:13,作 者: 黄兵

SQLAlchemy 如何更新数据库

最近修改了模型,没有更新数据库,提交数据报错,具体报错内容如下:

sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1054, "Unknown column 'body' in 'field list'") [SQL: 'INSERT INTO article (title, body, body_html, create_time, seo_link) VALUES (%s, %s, %s, %s, %s)'] [parameters: ('ccccccccc', "'''html'''", "<p>'''html'''</p>", <built-in method now of type object at 0x000000005C6A2DF0>, 'how_to_secert')] (Background on this error at: http://sqlalche.me/e/e3q8)


出现这个问题的原因是:

模型与数据库的关系映射有问题。

模型代码:

# 文章相关表
class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128))
    body = db.Column(db.Text)
    body_html = db.Column(db.Text)
    create_time = db.Column(db.DateTime, index=True)
    seo_link = db.Column(db.String(128))

    @staticmethod
    def on_changed_body(target, value, oldvalue, initiator):
        allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code',
                        'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
                        'h1', 'h2', 'h3', 'p']
        target.body_html = bleach.linkify(bleach.clean(
            markdown(value, output_format='html'),
            tags=allowed_tags, strip=True))


db.event.listen(Article.body, 'set', Article.on_changed_body)

数据库字段截图:


解决方案:

只需要更新数据库,使SQLAlchemy模型与数据库字段对应。

python manage.py db migrate -m "edit body to conetent"

注意上面需要双引号,单引号会报如下错误:

manage.py: error: too many arguments

提交修改之后需要更新数据库。

python manage.py db upgrade

查看一下数据库已经成功更新:


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - SQLAlchemy 如何更新数据库

分享到:

发表评论

评论列表