如果您的PostgreSQL版本足夠新(9.4+)且psycopg版本大於2.5.4,則所有的鍵都是字符串,並且值可以表示爲JSON,最好將其存儲到JSONB列中。然後,如果需要,列也可以搜索。只要創建該表只是作爲
CREATE TABLE thetable (
uuid TEXT,
dict JSONB
);
(...並根據需要自然地添加索引,主鍵等) 當發送詞典到PostgreSQL,你只需要與Json
適配器把它包起來;從PostgreSQL的接收時JSONB值將被自動轉換爲一個字典,這樣就插入將成爲
from psycopg2.extras import Json, DictCursor
cur = conn.cursor(cursor_factory=DictCursor)
cur.execute('INSERT into thetable (uuid, dict) values (%s, %s)',
['testName', Json({'id':'122','name':'test','number':'444-444-4444'})])
和選擇將是一樣簡單
cur.execute('SELECT dict FROM thetable where uuid = %s', ['testName'])
row = cur.fetchone()
print(row['dict']) # its now a dictionary object with all the keys restored
print(row['dict']['number']) # the value of the number key
隨着JSONB時,PostgreSQL可以更有效地存儲的值而不僅僅是將字典傾倒爲文本。另外,可以做查詢的數據,例如只需要選擇一些來自JSONB列字段:
>>> cur.execute("SELECT dict->>'id', dict->>'number' FROM thetable")
>>> cur.fetchone()
['122', '444-444-4444']
或者如果需要的話,你可以在查詢中使用它們:
>>> cur.execute("SELECT uuid FROM thetable WHERE dict->>'number' = %s',
['444-444-4444'])
>>> cur.fetchall()
[['testName', {'id': '122', 'name': 'test', 'number': '444-444-4444'}]]
那麼如果我需要返回整個字典對象,我可以這樣做返回行['字典']? – sbeyeler
@sbeyeler可以使用任何可以使用'json.dumps'的數據結構。 –