【问题标题】:How to import headerless csv into postgresql with django_postgres_copy?如何使用 django_postgres_copy 将无头 csv 导入 postgresql?
【发布时间】:2016-10-31 11:59:55
【问题描述】:

我有一个巨大的 csv 文件要导入 Postgres,我的 django 模型已经完成,我的问题是 csv 文件没有我可以映射到的任何标题,我正在尝试使用 postgres_copy @987654321 @ 为我做这件事,但我找不到没有标题的方法。

'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 标头。

我环顾四周,但到目前为止我找不到任何可以回答我的问题的东西。提前谢谢你。

【问题讨论】:

    标签: python django postgresql csv


    【解决方案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 加载到临时表中,并通过更强大的 SQL 将“清理”加载到模型表中。您的里程可能会有所不同...

    http://initd.org/psycopg/docs/cursor.html#cursor.copy_expert 还有https://www.postgresql.org/docs/9.5/static/sql-copy.html

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2017-03-11
      相关资源
      最近更新 更多