微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

动态类和sqlalchemy错误

如何解决动态类和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\",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)之前创建实例时,会发生这种情况。     

解决方法

        如果您创建一个函数来返回通常设置的类,则这会更容易。我已经尝试过类似的方法,并且可以正常工作:
def getNewTable( db,table ):
    class NewTable( Base ):
        __tablename__ = table
        __table_args__ = { \'schema\': db }
        id = Column( ...

    return NewTable

newClassInst = getNewTable( \'somedb\',\'sometable\' )
newRow = newClassInst( data )
    ,        如错误说明所述,此问题是由于缺少用于仪器的仪器功能接口引起的。我认为这实际上是由ѭ2引起的。 因此,这可以通过重建init来解决,而init不会通过ORM修改注入的函数。 转这个
#my init function
def tableinit(self,keyargs):
    self.__dict__ = dict(keyargs)
#my init function
def tableinit(self,**kwargs):
    self.__dict__.update(kwargs)
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。