3

If I read the docs correctly, then the FileField in Django does not know the content_type of the file: https://docs.djangoproject.com/en/2.1/ref/models/fields/

I would like to store files in a Django application, but I want to query the content_type.

Examples:

  • list all objects which have a file with content_type "application/pdf"
  • list all objects which have a file with content_type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

What is the most django-like way to handle this?

cezar
  • 11,616
  • 6
  • 48
  • 84
guettli
  • 25,042
  • 81
  • 346
  • 663

1 Answers1

4

Assuming you have a model as:

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

The field myfile is for storing files, and content_type is for storing the content-type of the corresponding file.

You could store the content_type type of a file by overriding the save() method of Foo model.

Django file field provides file.content_type attribute to handle the content_type type of the file. So change your model as:

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)



Now, you could query the ORM by using filter() as:

Foo.objects.filter(content_type='application/pdf')
cezar
  • 11,616
  • 6
  • 48
  • 84
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    probably it's about https://docs.djangoproject.com/en/2.2/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.content_type when file is stored in the request.FILES but FieldFile or FileField does not have a .content_type method. Hence, self.myfile.file.content_type will not return anything except error. – gek Jun 17 '20 at 14:19