我正在尝试编写一个日志系统,它使用动态类来创建表。获取创建的类,并创建表似乎工作正常,但尝试将条目放入其中会导致有关映射的错误消息,下面是示例代码和错误消息。
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:映射了'newTable'类,但此实例缺少检测。在调用sqlalchemy.orm.mapper(module.newTable)之前创建实例时会发生这种情况。
答案 0 :(得分:2)
如果您创建一个函数来返回正常设置的类,这会更容易。我尝试过类似的东西并且有效:
def getNewTable( db, table ):
class NewTable( Base ):
__tablename__ = table
__table_args__ = { 'schema': db }
id = Column( ...
return NewTable
newClassInst = getNewTable( 'somedb', 'sometable' )
newRow = newClassInst( data )
答案 1 :(得分:1)
这个问题是由于缺少orm的仪器功能接口引起的,如错误描述所示。它实际上是由self.__dict__ = dict(keyargs)
引起的。
所以这可以通过重构 init 来解决,它不会通过ORM修改注入的函数。
转过来
#my init function
def tableinit(self,keyargs):
self.__dict__ = dict(keyargs)
要
#my init function
def tableinit(self,**kwargs):
self.__dict__.update(kwargs)