我有一个大量的csv文件要导入Postgres,我的django模型已经完成了,我的麻烦是csv文件没有我可以映射到的任何标题,我试图使用postgres_copy http://django-postgres-copy.readthedocs.io/en/latest/为我这样做,但我找不到没有标题的方法。
'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 :(得分:1)
您可以直接转到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命令对数据格式和完整性很敏感 - 格式错误的日期,数字,bool以及完整性检查会导致加载失败。作为一种解决方法,我使用copy
加载到临时表中,并通过更强大的SQL对模型表进行“清理”加载。你的里程可能会有所不同......
参见http://initd.org/psycopg/docs/cursor.html#cursor.copy_expert 并https://www.postgresql.org/docs/9.5/static/sql-copy.html
希望这有帮助。