【问题标题】:Django: FileField, missing content_typeDjango:文件字段,缺少 content_type
【发布时间】:2019-01-26 10:07:29
【问题描述】:

如果我正确阅读了文档,那么 Django 中的 FileField 不知道文件的 content_type:https://docs.djangoproject.com/en/2.1/ref/models/fields/

我想在 Django 应用程序中存储文件,但我想查询 content_type。

例子:

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

处理这个最像 django 的方式是什么?

【问题讨论】:

    标签: django django-file-upload


    【解决方案1】:

    假设你有一个模型:

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

    myfile字段用于存储文件,content_type用于存储对应文件的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)
    
        def save(self, *args, **kwargs):
            self.content_type = self.myfile.file.content_type
            super().save(*args, **kwargs)



    现在,您可以使用 filter() 查询 ORM:

    Foo.objects.filter(<b>content_type='application/pdf'</b>)

    【讨论】:

    猜你喜欢
    • 2014-10-18
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2011-03-31
    • 2017-10-28
    相关资源
    最近更新 更多