将csv导入django模型

时间:2014-03-11 06:36:35

标签: django

我将模型定义为

class Event(models.Model):
    event_id=models.IntegerField(primary_key=True)
    OS_CHOICE=(('Win 2003','windows 2003'),
        ('Win 2008','Windows 2008'),
        ('Win XP','Windows XP'),
        ('Win VISTA','Win VISTA'),
        ('Win 2007','Windows 2007'),
        )
    windows=models.CharField(max_length=10,choices=OS_CHOICE,default='Win 2003')

    def __unicode__(self):
        return " %s, event_id :%s" \
            % (self.windows, self.event_id)
    class Meta:
        db_table= 'event'
        verbose_name_plural='events'

class Eventgroups(models.Model):
    event=models.ManyToManyField(Event)
    group_name=models.CharField(max_length=100)

    def __unicode__(self):
        return "%s,  %s" \
            % (self.group_name, self.event)
    class Meta:
        db_table= 'eventgroup'
        verbose_name_plural='eventgroups'

class Groups_import(models.Model):
    event_id=models.IntegerField()
    windows=models.CharField(max_length=100)
    group_name=models.CharField(max_length=100)

我想编写一个视图,使用上面的模型定义将csv导入数据库。将要求用户浏览到csv文件所在的位置,然后单击按钮以导入csv。 有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用:

请参阅how to import csv data into django models

或者您可以编写自己的例程:

# sudo code
file = request.FILES['fileUpload']
data = [row for row in csv.reader(file.read().splitlines())]
for raw in data:
    _, created = Event.objects.get_or_create(
            event_id=row[0],
            windows=row[1]
            )