Is it possible to create foreign keys with pandas to_sql

224 views Asked by At

I have two DataFrames that have a ForeignKey based relationship, a field in the first DataFrame is a ForeignKey to the Id of the second DataFrame. When I use pandas's to_sql method, The relationship is not created in the destination database. Is there a way to create the relationship with to_sql?

1

There are 1 answers

0
bmalbusca On

The pandas.to_sql() will only convert the data existing on your dataframe and it does not allow to select the foreign keys and consequently creating the relationship table. however you can solve this in two ways:

  1. Make a pandas.merge() to get the relationship table
  2. After converting pandas to sql, use sql library (e.g, sqlite) to create a relationship table with the foreign keys.

I hope this helps you.