2016-10-31 63 views
0

我有一個巨大的csv文件導入到Postgres中,我的django模型全部完成,我的麻煩是,csv文件沒有任何我可以映射的標題,並且我試圖使用postgres_copy http://django-postgres-copy.readthedocs.io/en/latest/這對我來說,但我找不到沒有標題的方法。如何使用django_postgres_copy將無頭文件csv導入到postgresql中?

'123131','data','data','d','d','123112','d' 

這就是我的csv的樣子。我有500萬行。如果還有其他方法,我也向他們開放。

from .models import MyModel 
from postgres_copy import CopyMapping 
from django.core.management.base import BaseCommand 
import os 

class DataToPostGres(BaseCommand): 
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
DATA_ROOT = os.path.join(BASE_DIR, 'data/bigcsv.csv') 

def handle(self, *args, **kwargs): 
    c = CopyMapping(
     # Give it the model 
     MyModel, 
     # The path to your CSV 
     DATA_ROOT, 
     # And a dict mapping the model fields to CSV headers 
     dict(name='NAME', number='NUMBER', dt='DATE') 
    ) 
    # Then save it. 
    c.save() 

這裏是我迄今爲止,但它顯然是不行的,因爲我不能我的模型字段映射到任何CSV頭。

我環顧四周,但到目前爲止找不到任何回答我的問題的東西。先謝謝你。

回答

0

您可以直接轉到psycopg2驅動程序,並直接使用copy命令(它允許您映射不帶標題的列)。喜歡的東西:

from django.db import connection 

sql = 'copy table_name (col1, col2, col3) from stdin with (format csv)' 
with open(DATA_ROOT) as infile: 
    with connection.cursor() as stmt: 
     stmt.copy_expert(sql, infile) 

指定要在它們出現在.csv順序的cols,但要注意,copy命令是數據格式化和完整性敏感 - 畸形的日期,數字,布爾變量,以及完整性檢查,會導致負載失敗。作爲一種解決方法,我使用copy加載到臨時表中,並通過更強大的SQL對模型表執行「清理」加載。你的情況可能會有所不同...

http://initd.org/psycopg/docs/cursor.html#cursor.copy_experthttps://www.postgresql.org/docs/9.5/static/sql-copy.html

希望這有助於。

相關問題