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:
What is the most django-like way to handle this?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With