Django:FileField,缺少 content_type

标签 django django-file-upload

如果我正确阅读了文档,那么 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 的方法是什么?

    最佳答案

    假设你有一个模型:

    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 覆盖 的文件类型save() 的方法Foo 模型。

    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(content_type='application/pdf')

    关于Django:FileField,缺少 content_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51928008/

    相关文章:

    python - django:管理网址中的 Nonelogout

    python - pip 安装 Django

    django - 手动将文件传递给 Django Form

    Django 文件字段 : How to return filename only (in template)

    Django:使用 python-magic 在模型中进行文件字段验证

    python - Django 在多对多关系中获取相关对象

    django - OperationalError 无法连接到服务器

    django - 使用 gevent 执行池的 celery 任务的 SynchronousOnlyOperation

    django - 在保存对象之前处理文件上传

    Django:验证时忘记/删除了 FileField 的表单字段输入