Skip to content
Advertisement

Primary key constraint gets removed when creating postgres table from pandas dataframe

I am trying to create few tables in Postgres from pandas dataframe but I am kept getting this error.

After looking into this problem for hours, i finally found that when I am inserting the data into parent table from pandas dataframe, the primary key constraint gets removed for some reasons and due to that I am getting this error when trying to refernece it from another table.

But I am not having this problem when I am using pgAdmin4 to create the table and inserting few rows of data manually.

enter image description here enter image description here

you can see when I created the tables using pgAdmin, the primary key and foreign keys are getting created as expected and I have no problem with it.

But when I try to insert the data from pandas dataframe using psycopg2 library, the primary key is not getting created.

I Can’t able to understand why is this happening.

enter image description here

The code I am using to create the tables –

Advertisement

Answer

I think the problem is to_sql(if_exists="replace"). Try using to_sql(if_exists="append") – my understanding is that “replace” drops the whole table and creates a new one with no constraints.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement