解決策が見つかりませんでした。私は今、他のテーブルから抽出するのではなく、挿入する情報を持つタプルのリストを渡し、問題はなくなりました。PostgreSQL false IntegrityError
私は現在、テーブルを編集するコードを書いています。私は挿入するいくつかの行の情報を持っていますが、私はを第4要素に、順序にかかわらず取得し続けます。ここで
は、私はテーブルを作成する方法である:
今CREATE TABLE segment_speed_live_layer(segment_id INTEGER PRIMARY KEY,
geom GEOMETRY(LINESTRING, 4326),
speed INTEGER);
ことがなく、連番のすることはできませんので、segment_idには、別のテーブルに一致する必要があります。
def update_layer():
segment_cursor = connection.cursor()
segment_query = 'SELECT segment_id, speed FROM segment_speed_live ORDER BY segment_id'
exists_cursor = connection.cursor()
exists_query = 'SELECT EXISTS(SELECT 1 FROM segment_speed_live_layer WHERE segment_id=%s)'
insert_cursor = connection.cursor()
insert_query = """INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT %(segment_id)s, geom_way, %(speed)s
FROM other_table
WHERE segment_id=%(segment_id)s"""
update_query = 'UPDATE segment_speed_live_layer SET speed=%(speed)s WHERE segment_id=%(segment_id)s'
segment_cursor.execute(segment_query)
for row in segment_cursor:
segment_id, speed = row
exists_cursor.execute(exists_query, (segment_id,))
exists = exists_cursor.fetchone()[0]
query = update_query if exists else insert_query
print(segment_id, speed, exists)
print(insert_cursor.mogrify(query, {'segment_id': segment_id, 'speed': speed}))
insert_cursor.execute(query, {'segment_id': segment_id, 'speed': speed})
print(insert_cursor.statusmessage)
connection.commit()
速度で注文すると、4番目の要素ではなく5番目の要素で失敗します。より低いIDで失敗するようです。これはテスト段階ですから、テーブルを複数回削除して再作成しました。私はKNOW
このテーブルには指定されたIDの行がありません。
私はthis questionとthis blog postを読んでいますが、自分のIDが逐次的または自動的に割り当てられていないため、ソリューションが機能しません。
私の唯一の考えは、PRIMARY KEY
という制約を削除することですが、それは理想的ではありません。参照用
出力:
(243, 69, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 243, geom_way, 69
FROM other_table
WHERE other_table.segment_id=243
INSERT 0 1
(680, 9, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 680, geom_way, 9
FROM other_table
WHERE other_table.segment_id=680
INSERT 0 1
(11599, 42, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 11599, geom_way, 42
FROM other_table
WHERE other_table.segment_id=11599
INSERT 0 1
(16399, 40, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 16399, geom_way, 40
FROM other_table
WHERE other_table.segment_id=16399
をother_table' 'にどのように多くの行がありますか? –