使用djang将csv文件中的数据添加到数据库

2024-06-25 06:20:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下Django模型:

class TraxioRelations(models.Model):
    corgemeente = models.CharField(max_length=100, null=True)
    coradres = models.CharField(max_length=255, null=True)
    corhuisnr = models.CharField(max_length=10, null=True, blank=True)

该模型在数据库中创建一个id表,如下所示: enter image description here

现在我想把csv文件中的记录添加到这个模型中。csv文件如下:

enter image description here

我使用copy命令如下:

COPY master_traxiorelations(corgemeente, coradres, corhuisnr)
FROM '/path/to/file.csv' CSV HEADER delimiter ';' encoding 'ISO-8859-1';

当我执行它时,我得到一个错误如下:

[2017-08-21 15:50:49] [22P04] ERROR: extra data after last expected column

但是当我添加一个idcopy命令时,因此COPY master_traxiorelations(id, corgemeente, coradres, corhuisnr)

以及csv文件:

enter image description here

那就行了。你知道吗

如何将文件中的数据添加到数据库中,而不将id添加到copy命令和csv文件中?你知道吗


Tags: 文件csv模型命令idtruemodelsnull
1条回答
网友
1楼 · 发布于 2024-06-25 06:20:42

我通过向模型中添加id解决了这个问题,如下所示:

id = models.AutoField(primary_key=True)

添加id = models.AutoField(primary_key=True)可以自动增加id。因此,我的模型如下所示:

 class TraxioRelations(models.Model):
    id = models.AutoField(primary_key=True)
    corgemeente = models.CharField(max_length=100, null=True)
    coradres = models.CharField(max_length=255, null=True)
    corhuisnr = models.CharField(max_length=10, null=True, blank=True)

然后copy命令不在csv文件中添加id列。你知道吗

COPY master_traxiorelations(corgemeente, coradres, corhuisnr)
FROM '/path/to/file.csv' CSV HEADER delimiter ';' encoding 'ISO-8859-1';

如果其他人也有同样的问题,希望这能有所帮助。你知道吗

相关问题 更多 >