【问题标题】:Why an UnmappedInstanceError while populating a database using Flask-SQLAlchemy?为什么在使用 Flask-SQLAlchemy 填充数据库时出现 UnmappedInstanceError?
【发布时间】:2014-08-16 09:57:15
【问题描述】:

我是 SQLAlchemy 的新手,我在当前项目中使用 Flask-SQLAlchemy。我遇到了一个让我难过的错误:

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'flask_sqlalchemy._BoundDeclarativeMeta' is not mapped; was a class (app.thing.Thing) supplied where an instance was required?

我已经尝试更改 instatiation 中的符号,并移动一些东西。问题是否与此question 或其他有关?

这是我的模块 (thing.py),其类继承自 Flask-SQLAlchemy 的 db.Model(如 SQLAlchemy 的 Base 类):

from app import db

class Thing(db.Model):
    indiv_id = db.Column(db.INTEGER, primary_key = True)
    stuff_1 = db.Column(db.INTEGER)
    stuff_2 = db.Column(db.INTEGER)
    some_stuff = db.Column(db.BLOB)

    def __init__():
        pass

这是我在thing_wrangler.py 模块中填充数据库的调用:

import thing
from app import db

def populate_database(number_to_add):
    for each_thing in range(number_to_add):
        a_thing = thing.Thing
        a_thing.stuff_1 = 1
        a_thing.stuff_2 = 2
        a_thing.some_stuff = [1,2,3,4,5]
        db.session.add(a_thing)
    db.session.commit()

【问题讨论】:

    标签: python orm flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您需要创建模型的实例。而不是a_thing = thing.Thing,它应该是a_thing = thing.Thing()。注意括号。由于您覆盖了__init__,因此您还需要修复它,以便将self 作为第一个参数。

    【讨论】:

      猜你喜欢
      • 2014-06-23
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 2016-06-20
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      相关资源
      最近更新 更多