Django:文件字段,缺少内容类型

Django:文件字段,缺少内容类型,django,django-file-upload,Django,Django File Upload,如果我正确阅读了文档,那么Django中的文件字段不知道文件的内容类型: 我想在Django应用程序中存储文件,但我想查询内容类型 示例: 列出包含内容类型为“application/pdf”的文件的所有对象 列出具有“application/vnd.openxmlformats of icedocument.spreadsheetml.sheet”内容类型文件的所有对象 最像django的处理方法是什么?假设您的模型是: class Foo(models.Model): myfil

如果我正确阅读了文档,那么Django中的文件字段不知道文件的内容类型:

我想在Django应用程序中存储文件,但我想查询内容类型

示例:

  • 列出包含内容类型为“application/pdf”的文件的所有对象
  • 列出具有“application/vnd.openxmlformats of icedocument.spreadsheetml.sheet”内容类型文件的所有对象

最像django的处理方法是什么?

假设您的模型是:

class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)
class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)

    def save(self, *args, **kwargs):
        self.content_type = self.myfile.file.content_type
        super().save(*args, **kwargs)
字段
myfile
用于存储文件,
content\u type
用于存储相应文件的内容类型。

您可以通过覆盖
Foo
模型的
save()
方法来存储文件的
内容类型。


Django file字段提供
file.content\u type
属性来处理文件的
content\u type
类型。因此,将您的模型更改为:

class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)
class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)

    def save(self, *args, **kwargs):
        self.content_type = self.myfile.file.content_type
        super().save(*args, **kwargs)
可能是关于文件何时存储在request.FILES中,但FieldFile或FileField没有.content\u类型的方法。因此,self.myfile.file.content_type将不会返回除error之外的任何内容。