Django:FileField,缺少content_type

3
如果我正确地阅读了文档,那么Django中的FileField不知道文件的content_type:https://docs.djangoproject.com/en/2.1/ref/models/fields/ 我想在Django应用程序中存储文件,但是我想查询content_type。
例子:
  • 列出所有具有content_type为“application/pdf”的文件的对象
  • 列出所有具有content_type为“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”的文件的对象
最Django风格的处理方式是什么?
1个回答

4
假设您有以下模型:
class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)

字段myfile用于存储文件,content_type用于存储相应文件的内容类型。

您可以通过重写Foo模型的save()方法来存储文件的content_type类型。

Django文件字段提供了file.content_type属性来处理文件的content_type类型。因此,请更改您的模型如下:

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

    <b>def save(self, *args, **kwargs):
        self.content_type = self.myfile.file.content_type
        super().save(*args, **kwargs)</b>

现在,您可以使用filter()查询ORM,例如:
Foo.objects.filter(<b>content_type='application/pdf'</b>)

1
可能是关于https://docs.djangoproject.com/en/2.2/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.content_type 当文件存储在request.FILES中时,但FieldFile或FileField没有.content_type方法。因此,self.myfile.file.content_type除了错误之外将不会返回任何内容。 - gek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接