[英]Adding data from csv file to database using django
I have Django model as follows: 我有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)
That model creates a table in the database with id
as follows: 该模型在数据库中创建一个表,其
id
如下:
Now I want to add records from csv file to that model. 现在,我想将记录从csv文件添加到该模型。 The csv file is as follows:
csv文件如下:
I use copy
command as follows: 我使用
copy
命令如下:
COPY master_traxiorelations(corgemeente, coradres, corhuisnr)
FROM '/path/to/file.csv' CSV HEADER delimiter ';' encoding 'ISO-8859-1';
And when I execute it, I get an error as follows: 当我执行它时,出现如下错误:
[2017-08-21 15:50:49] [22P04] ERROR: extra data after last expected column
But when I add an id
to copy
command, thus COPY master_traxiorelations(id, corgemeente, coradres, corhuisnr)
但是,当我添加一个
id
来copy
命令时,因此是COPY master_traxiorelations(id, corgemeente, coradres, corhuisnr)
And to csv
file also: 并且也要
csv
文件:
Then it works fine. 然后工作正常。
How can I add the data from file to the database, without adding id to copy command and to csv file? 如何将文件中的数据添加到数据库中,而无需在复制命令和CSV文件中添加ID?
I solved it adding id
to the model as follows: 我解决了将
id
添加到模型的问题,如下所示:
id = models.AutoField(primary_key=True)
Adding id = models.AutoField(primary_key=True)
enables auto incrementation of the id. 添加
id = models.AutoField(primary_key=True)
启用ID的自动递增。 Thus my model looks like : 因此,我的模型如下所示:
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)
And then copy
command works without adding id column in the csv file. 然后,
copy
命令无需在csv文件中添加id列即可工作。
COPY master_traxiorelations(corgemeente, coradres, corhuisnr)
FROM '/path/to/file.csv' CSV HEADER delimiter ';' encoding 'ISO-8859-1';
Hope that this helps if someone else has the same problem. 希望如果有人遇到同样的问题,这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.