简体   繁体   English

使用django将CSV文件导入postgres

[英]import CSV file into postgres using django

I am trying to import csv file into postgres DB using Django . 我正在尝试使用Django将csv文件导入postgres DB。

I try following function: 我尝试以下功能:

import os
from django.db import models
import psycopg2
from postgres_copy import CopyMapping

host = 'localhost'
port = '5432'
dbname = 'sellerhub'
username = 'postgres'
password = 'postgres'


class Reports:
    def __init__(self):
        global host, port, dbname, username, password
        try:
            self.db_conn = psycopg2.connect("host=%s port=%s dbname=%s user=%s password=%s" %(host, port, dbname, username, password))
        except psycopg2.OperationalError:
            print "Database Not Found Or the Credentials are wrong."
        self.cur = self.db_conn.cursor()
def saveUploadedInventory(self, inventory_file):
        #print "Inventory File"
        with open('uploaded_inventory_sheet.csv','wb+') as destination:
            for chunk in inventory_file.chunks():
                destination.write(chunk)
        #print "Inventory Saved."
        copy_sql = """copy fk_invent_temp from stdin WITH CSV HEADER DELIMITER as ',' """
        #print "query created"
        with open('uploaded_inventory_sheet.csv','r') as pmt_file:
            self.cur.copy_expert(sql=copy_sql, file=pmt_file)
        #print "file uploades"
        os.system('rm uploaded_inventory_sheet.csv')
        #print "removes file"

and setting.py setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'sellerhub',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': '5432',
        }
    }

this function is executed completly with no error, 该函数完全执行,没有错误,

but there is no data in fk_invent table . 但是fk_invent表中没有数据。

If i directly import that file using PGAdmin3 UI that is uploaded successfully . 如果我直接使用成功上传的PGAdmin3 UI导入该文件。 Pls any body can tell what i am doing wrong ? 请问有谁能告诉我我做错了吗?

I get temporary solution by inserting line by line: 我通过逐行插入获得临时解决方案:

with open('uploaded_inventory_sheet.csv','wb+') as destination:
            for chunk in inventory_file.chunks():
                destination.write(chunk)
        print "Inventory Saved."
        reader = csv.reader(open('uploaded_inventory_sheet.csv','rb'))
        count = 0 
        for row in reader:
            if count == 0:
                count=1
                continue
            # print row[0],"\n"
            count = count +1
            try:
                self.cur.execute("""INSERT into  fk_payment_temp values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16],row[17],row[18],row[19],row[20],row[21],row[22],row[23],row[24],row[25],row[26],row[27],row[28],row[29],row[30],row[31],row[32],row[33],row[34],row[35],row[36],row[37],row[38],row[39],row[40],row[41],row[42],row[43],row[44]))
                print "INSERT into  fk_payment_temp values('",row[0],"','",row[1],"''",row[2],"','",row[3],"''",row[4],"','",row[5],"''",row[6],"','",row[7],"''",row[8],"','",row[9],"''",row[10],"','",row[11],"''",row[12],"','",row[13],"''",row[14],"','",row[15],"''",row[16],"','",row[17],"''",row[18],"','",row[19],"''",row[20],"','",row[21],"''",row[22],"','",row[23],"''",row[24],"','",row[25],"''",row[26],"','",row[27],"''",row[28],"','",row[29],"''",row[30],"','",row[31],"''",row[32],"','",row[33],"''",row[34],"','",row[35],"''",row[36],"','",row[37],"''",row[38],"','",row[39],"''",row[40],"','",row[41],"''",row[42],"','",row[43],"''",row[44],"','",row[45],"')"
            except:
                pass
        print count
        self.cur.callproc("flip_payment_test")
        self.cur
        self.db_conn.commit()

        print "file uploades"
        os.system('rm uploaded_inventory_sheet.csv')
        print "removes file" 

The simplest and cleanest solution is to import a json fixture file with Django manage.py command. 最简单,最干净的解决方案是使用Django manage.py命令导入json夹具文件。 So I'd recommend you converting your CSV file to json and load it to database with manage.py loaddata command: 因此,我建议您将CSV文件转换为json并使用manage.py loaddata命令将其加载到数据库中:

python manage.py loaddata yourfile.json

You can find CSV to json converters all over the Internet. 您可以在整个Internet上找到CSV到json转换器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM