在postgresql中使用Sqlalchemy插入JSONB数组

时间:2017-06-29 19:48:26

标签: python postgresql sqlalchemy psycopg2 jsonb

我在postgresql中插入JSONB数组时遇到问题。 该问题与Issue with Sqlalchemy and inserting array of jsonb to postgresql有关,但尚无答案。

根据http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#using-json-jsonb-with-array的指示,该列定义为类型:

myKeyOfJsonbArray=db.Column(CastingArray(JSONB)) 

与班级:

class CastingArray(ARRAY):
    def bind_expression(self, bindvalue):
        return cast(bindvalue, self)

我将init函数重新定义为:

def __init__(self, attributes):
    for key in attributes:
        if key==myKeyOfJsonbArray:
            temp=[]
            for object in attributes[key]:
                temp.append(object)
            print str(temp)
            setattr(self,key,temp)
        else : 
            ...

print语句可以很好地打印数组:
[{u'price_list_id':u'retail',u'value':u'10.0'}]

但在尝试设置属性时,psycopg2返回无法调整类型'dict'。

一个cast temp.append(cast(object,JSONB))返回不能适应类型'Cast'... 我尝试了大量的解决方案(例如,使用jsonb_build_object),但我无法弄明白。 如果有人已经遇到这个问题请谢谢!

修改

作为行

psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)

似乎成功了,一个更复杂的词典仍然会导致问题。

0 个答案:

没有答案