如果我正确阅读了文档,那么 Django 中的 FileField 不知道文件的 content_type:https://docs.djangoproject.com/en/2.1/ref/models/fields/
我想在 Django 应用程序中存储文件,但我想查询 content_type。
例子:
处理这个问题的最像 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/