Skip to content
Advertisement

inserting into Postgres table with a foreign key using python

I am trying to insert data from a json into my postgres table with python (psycopg2). This json is huge and now I am questioning what the proper way is to insert all of this data.

What makes it difficult for me is that the table has a reference to another table. I want to refer to the id of that table based on one of the values in my json.

Details of my question:

JavaScript

where this table entities is already filled with data like this:

JavaScript

The table that I want to fill with the data from the json:

JavaScript

part of the json:

JavaScript

The “code” key in the json is already located in the entities table, so in the end_of_days.entity_id I want to refer to the id from the entities table based on this “code” value.

It there a pretty solution for this with psycopg2? Normally I would just use psycopg2.extras.execute_values() but I think this won’t work in this specific situation.

(P.S. this is my first time posting on stackoverflow so if I need to specify something, or structure my question differently, please let me know.)

Advertisement

Answer

This is not really an answer but a suggestion for a possible way to handle this. While figuring this out break the JSON data into smaller chunks for testing purposes. The idea:

Create a staging table that you directly INSERT the JSON from the file(s) into jsonb fields in the table. Use the JSON capabilities of psycopg2. Then you could use the JSON processing functions from here JSON Function in ‘Table 9.47. JSON Processing Functions’ to modify and move the data to market.end_of_days

UPDATE

I found it easier to do something like:

JavaScript
JavaScript
Advertisement