copy dataframe to postgres table with column that has defalut value

允我心安 提交于 2019-12-11 07:30:00

问题


I have the following postgreSql table stock, there the structure is following with column insert_time has a default value now()

|    column   |  pk |    type   |
+-------------+-----+-----------+
| id          | yes | int       |
| type        | yes | enum      |
| c_date      |     | date      |
| qty         |     | int       |
| insert_time |     | timestamp |

I was trying to copy the followning df

|  id | type |    date    | qty  |
+-----+------+------------+------+
| 001 | CB04 | 2015-01-01 |  700 |
| 155 | AB01 | 2015-01-01 |  500 |
| 300 | AB01 | 2015-01-01 | 1500 |

I was using psycopg to upload the df to the table stock

cur.copy_from(df, stock, null='', sep=',')
conn.commit()

getting this error.

DataError: missing data for column "insert_time"
CONTEXT:  COPY stock, line 1: "001,CB04,2015-01-01,700"

I was expecting with the psycopg copy_from function, my postgresql table will auto-populate the rows along side the insert time.

|  id | type |    date    | qty  |     insert_time     |
+-----+------+------------+------+---------------------+
| 001 | CB04 | 2015-01-01 |  700 | 2018-07-25 12:00:00 |
| 155 | AB01 | 2015-01-01 |  500 | 2018-07-25 12:00:00 |
| 300 | AB01 | 2015-01-01 | 1500 | 2018-07-25 12:00:00 |

回答1:


You can specify columns like this:

cur.copy_from(df, stock, null='', sep=',', columns=('id', 'type', 'c_date', 'qty'))



来源:https://stackoverflow.com/questions/51522105/copy-dataframe-to-postgres-table-with-column-that-has-defalut-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!