SQLAlchemy ORM 使用问题,请高手指教。

狗操_我今年大三它妈 发布于 2015/05/28 15:05
阅读 862
收藏 1

动态创建mapper 的代码:

def VendorDev(tname):
    #if g_vendordev.has_key(tname):
    #    return g_vendordev[tname]
    #g_vendordev[tname] =
    return type("NewClass",(BaseModel,),{"__tablename__":tname,
                                           #"__init__":settnlname,
                                           "extend_existing":True,
                                           "devid":Column(UUID,primary_key=True,unique=True,nullable=False),
                                           "is_active":Column(Boolean,nullable=False,default=True),
                                           "last_login_time":Column(TIMESTAMP,nullable=False,default=datetime.now()),
                                           "is_online":Column(Boolean,nullable=False,default=True),
                                           "chost":Column(VARCHAR(22),nullable=False,default=''),
                                           "data":Column(BYTEA,default='')
                                           })
    #return g_vendordev[tname]

我用多进程调用会出如下waring:

SAWarning: This
 declarative base already contains a class with the same class name and module name as __main__.NewClass, and will be replaced in the string-lookup ta
ble.

VendorDev 通传入的参数名,创建相应的表,且与表mapper的类。

      session = Session()
        BaseModel.metadata.clear()
        newdev = VendorDev(res.vendor)(devid=res.tuid,chost = "%s:%d" % (res.host[0],res.host[1]),last_login_time=datetime.now())
        
#        newdev.devid = res.tuid
#        newdev.chost = "%s:%d" % (res.host[0],res.host[1])
#        newdev.last_login_time = datetime.now()
        session.merge(newdev)
        session.commit()
        session.close()

为什么不用 session.add(newdev) 而用session.merge(newdev),是为了防止相同的primary_key .具体的区别请高手指教一下。






加载中
0
junanhonglei
junanhonglei
我没用过动态创建,但是明显提示的错误是因为你 重复创建同一个类NewClass。add会新添加一个条目,merge则会判定是否存在,具体可以参考 http://stackoverflow.com/questions/1849567/can-sqlalchemys-session-merge-update-its-result-with-newer-data-from-the-data 
返回顶部
顶部