使用django将CSV文件导入postgres

时间:2015-11-09 12:41:28

标签: python django postgresql csv

我正在尝试使用Django将csv文件导入postgres DB。

我尝试以下功能:

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"

setting.py

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

这个函数完全没有错误地执行,

但fk_invent表中没有数据。

如果我使用成功上传的PGAdmin3 UI直接导入该文件。 请问任何身体可以告诉我做错了什么?

2 个答案:

答案 0 :(得分:3)

我通过逐行插入来获得临时解决方案:

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" 

答案 1 :(得分:0)

最简单,最干净的解决方案是使用Django json命令导入manage.py fixture文件。因此,我建议您将CSV文件转换为json并使用manage.py loaddata命令将其加载到数据库:

python manage.py loaddata yourfile.json

您可以在互联网上找到CSV到json转换器。

相关问题