在模型保存上解析前N行CSV

时间:2017-08-16 16:09:14

标签: python django csv django-models

我有一个用户可以上传CSV的模型,但由于文件有时可能太大,我想解析上传的CSV的前5行并创建新的CSV文件。这将作为一个示例文件,稍后将更小更快地使用。

这就是我models.py的样子:

from django.db import models

class Source(models.Model):
    file = models.FileField()
    sample = models.FileField(blank=True, null=True)
    name = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        # I want to parse the 'file' field and write it to 'sample' here


        super(Source, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

基本上在模型的保存功能中,我想解析file字段的前5行并取前5行,创建CSV并将其上传到sample字段。有关如何实现这一目标的任何想法?感谢。

1 个答案:

答案 0 :(得分:0)

import csv
import io
from django.core.files.base import ContentFile
from django.db import models

class Source(models.Model):
    file = models.FileField()
    sample = models.FileField(blank=True, null=True)
    name = models.CharField(max_length=255)
    _generate_sample = True

    def save(self, *args, **kwargs):
        super(Source, self).save(*args, **kwargs)
        if self.file and self._generate_sample:
            with open(self.file.path) as f:
                reader = csv.reader(f)
                lines = [next(reader) for x in xrange(5)]
            output = io.BytesIO()
            writer = csv.writer(output)
            writer.writerows(lines)
            self._generate_sample = False
            self.sample.save('short.csv', ContentFile(output.getvalue()))

    def __str__(self):
        return self.name