Django Rest Framework读取文件上传

时间:2016-01-16 21:35:59

标签: django django-rest-framework

我需要阅读csv文件的内容并保存到模型中。

# MODEL
class FileUpload(models.Model):
    datafile = models.FileField(upload_to=file_path_name)


# SIGNAL TO READ THE FILEUPLOAD INSTANCE
@receiver(post_save, sender=FileUpload)
def fileupload_post_save(sender, instance, *args, **kwargs):
    with open(instance.datafile, 'rb') as f:
        reader = csv.DictReader(f, delimiter='\t')
        for row in reader:
            print row

序列化文件。

# SERIALIZER
class FileUploadSerializer(serializers.ModelSerializer):

    class Meta:
    model = FileUpload

当我上传文件时,会出现此错误。

Got a `TypeError` when calling `FileUpload.objects.create()`. 
This may be because you have a writable field on the serializer class that is not a valid argument to `FileUpload.objects.create()`. You may need to make the field read-only, or override the FileUploadSerializer.create() method to handle this correctly.
Original exception text was: coercing to Unicode: need string or buffer, FieldFile found.

open()方法不应该打开这个FileField文件的实例吗?

有没有人有更好的解析这个文件的想法?我上传文件,然后阅读或可以在保存之前阅读?谢谢!

2 个答案:

答案 0 :(得分:2)

这是解决方案。有必要将请求直接传递给DictReader:

if serializer.is_valid():
    data = self.request.data.get('datafile')
    reader = csv.DictReader(data, delimiter='\t')
    for row in reader:
        print row['customer']

答案 1 :(得分:0)

FieldFile是存储在FileField上的数据。如果您希望使用Python open方法打开它,则应该调用FieldFile.open()。该错误来自您的保存后信号处理程序,因为open需要文件名,而您传递的是FieldFile