0

I have a postgresql table:

create table if not exists public.test
(
    id integer,
    name varchar,
    months jsonb
);

I have a json:

[
    {
        "id": 1,
        "name": "name_tset",
        "months": [
            {
                "month": 7,
                "year": 2024,
                "days_in_month": 29,
                "fact": "0",
            }
        ]
    },
    ...
]

When I want to insert data, the error "can't adapt type 'dict'" appears. I know it's because of the "month" dictionary list, but how do I add my code to make it work? Without "month", the insertion into the table is successful.

My code:

for d in data:
    columns_list = list(d.keys())
    insert_query = sql.SQL("INSERT INTO {schema}.{table_name} ({columns}) VALUES ({values})").format(
        schema=sql.Identifier(f'{schema}'),
        table_name=sql.Identifier(f'{table_name}'),
        columns=sql.SQL(",").join(map(sql.Identifier, columns_list)),
        values=sql.SQL(",").join(map(sql.Placeholder, columns_list))
    )
    cursor.execute(insert_query, d)

1

1 Answer 1

0

One way to do this:

import psycopg2
from psycopg2.extras import Json
from psycopg2 import SQL

con = psycopg2.connect(dbname='test', user='postgres', port=5432)
cur = con.cursor()

data = [
    {
        "id": 1,
        "name": "name_tset",
        "months": [
            {
                "month": 7,
                "year": 2024,
                "days_in_month": 29,
                "fact": "0",
            }
        ]
    }
]

columns_list = list(data[0].keys())
schema = "public"
table_name = "test"

insert_query = sql.SQL("INSERT INTO {schema}.{table_name} ({columns}) VALUES ({values})").format(
        schema=sql.Identifier(schema),
        table_name=sql.Identifier(table_name),
        columns=sql.SQL(",").join(map(sql.Identifier, columns_list)),
        values=sql.SQL(",").join(map(sql.Placeholder, columns_list))
    )

for d in data:
    cur.execute(insert_query, {"id": d["id"], "name": d["name"], "months": Json(d["months"])}

con.commit()

The above pulls the dict apart to allow for using the Json adaptation function on the months data. For more on JSON adaptation see JSON

This yields:

select * from test ;
-[ RECORD 1 ]----------------------------------------------------------
id     | 1
name   | name_tset
months | [{"fact": "0", "year": 2024, "month": 7, "days_in_month": 29}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.