gpt4 book ai didi

python - 动态类和 sqlalchemy 错误

转载 作者:行者123 更新时间:2023-11-30 23:52:01 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com