python - 动态类和 sqlalchemy 错误

标签 python sqlalchemy

我正在尝试编写一个日志系统,它使用动态类来创建表。创建类和创建表似乎工作正常,但尝试将条目放入其中会导致有关映射的错误消息,下面是示例代码和错误消息。

Base = declarative_base()

#my init function
def tableinit(self,keyargs):
    self.__dict__ = dict(keyargs)

#table creation
tableName = "newTable"
columnsDict["__tablename__"] = tableName
columnsDict["__init__"] = tableinit
columnsDict["id"] = Column("id",Integer, autoincrement = True, nullable = False, primary_key=True)
columnsDict["pid"] = Column("pid",Integer, ForeignKey('someparenttable.id'))  #someparenttable is created with a hard coded class
newTable = type(tableName,(Base,),columnsDict)
tableClassDict[tableName]=newTable

#when doing an entry
newClassInst = subEntryClassDict[tableName]
newEntry = newClassInst(dataDict)
entryList.append(newEntry)  # this is called in a for loop with the entries for someparenttable's entries also

self.session.add_all(entryList) # at this point the error occurs

错误:

UnmappedInstanceError: Class 'newTable' is mapped, but this instance lacks instrumentation. This occurs when the instance is created before sqlalchemy.orm.mapper(module.newTable) was called.

最佳答案

如果您创建一个函数来返回您通常设置的类,这会更容易。我已经尝试过类似的方法并且有效:

def getNewTable( db, table ):
    class NewTable( Base ):
        __tablename__ = table
        __table_args__ = { 'schema': db }
        id = Column( ...

    return NewTable

newClassInst = getNewTable( 'somedb', 'sometable' )
newRow = newClassInst( data )

关于python - 动态类和 sqlalchemy 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474549/

相关文章:

Python 推特包 : get error code

python - 在 Python 中将 url 请求输出写入 csv

python - 使用带公钥和密码的 SSH 隧道,使用 SQLAlchemy 连接到远程 PostgreSQL 数据库,所有这些都来自 Windows 机器

python - 撤消上一次 Alembic 迁移

python - 更改 Django 设置后 uwsgi 不会重新加载

python - skimage 调整大小更改数组的总和

python - 为什么在 python 队列消耗完所有工作后不释放线程

python - 混合 Cython 类和 SqlAlchemy

python - sqlalchemy 中的内部连接与连接加载

database - 如何使用Flask SQLALchemy中的“使用历史记录表版本化”。最好有一些代码示例