签署:models.py 看起来如此:
class Representative(models.Model):
parliament = models.CharField(max_length=128)
name = models.CharField(max_length=128)
country = models.CharField(max_length=128)
party_group = models.CharField(max_length=128)
national_party = models.CharField(max_length=128)
position = models.CharField(max_length=128)
然后可以管理<代码>python。 ll/条码:
import csv
from your_app.models import Representative
# If you re using different field names, change this list accordingly.
# The order must also match the column order in the CSV file.
fields = [ parliament , name , country , party_group , national_party , position ]
for row in csv.reader(open( your_file.csv )):
Representative.objects.create(**dict(zip(fields, row)))
你也做了。
<>Addendum (edit)
Per Thomas s request, here s an Interpretation of what **dict(zip(fields,row))
:
最初,<代码>fields 载有我们界定的外地名称清单,row
载有一份价值清单,该清单代表了CSV档案中的目前行文。
fields = [ parliament , name , country , ...]
row = [ 7 , Marta Andreasen , United Kingdom , ...]
>>> zip(fields, row)
[( parliament , 7 ), ( name , Marta Andreasen ), ( country , United Kingdom ), ...]
<代码>字典>功能只是将奶制品清单转换成字典。
>>> dict(zip(fields, row))
{ parliament : 7 , name : Marta Andreasen , country : United Kingdom , ...}
<代码>**>是将字典转换成功能的关键词表的一种方式。 www.un.org/spanish/ga/president 例如,电话create (**dict(zip(field, row)))
相当于:
create(parliament= 7 , name= Marta Andreasen , country= United Kingdom , ...)
希望这种明亮点。