Search Here

How to use self.env.cr.copy_from function to save data in database

In this tutorial I will show you how to save or insert data into the database table using odoo "copy_from" function. Odoo provide this "copy_from" function in "self.env.cr" (current database courser).




How to use self.env.cr.copy_from function to save data in database

What does self.env.cr.copy_from do?

The copy_from function takes almost four parameters.

Recommend: 


  1. CSV File: Takes content that need to be stored into the database table
  2. Table Name: Name of the table, where to stores the CSV content
  3. Separator: Symbol that distinguish between columns e.g. (|,;,etc)
  4. Column: Column of the table in which CSV data to be inserted

Recommend: 

What we are going to do?

We are going to save or insert CSV data into the table using "self.env.cr.copy_from". To do this we need to do following activity.

  1. Create table using "self.env.cr.execute"
  2. Open CSV file 
  3. Create list of column (fourth parameter of "copy_from" function)
  4. Copy CSV data into table using "self.env.cr.copy_from"
  5. Close CSV file

self.env.cr.execute(""" CREATE TABLE IF NOT EXISTS your_table(
count decimal, mean decimal, std decimal, min decimal, twentyfive decimal,
fifty decimal, seventyfive decimal, max decimal, cv decimal,
uid integer, report_type text,name text)""")
self.env.cr.commit()
csv_file= open(filepath,"r")
columns=['count','mean','std','min','twentyfive','fifty','seventyfive','max','cv','uid','report_type','name']
self.env.cr.copy_from(csv_file, 'your_table', sep='|', columns=columns)
self.env.cr.commit()
csv_file.close()
How to use self.env.cr.copy_from function to save data in database

Don,t forgot to share, keep sharing keep learning

Post a Comment

2 Comments

  1. HI,what if my table exit what should do ? How i can run this function ?

    ReplyDelete