How do I perform a Django queryset filter looking for blank files in "FileField" fields?
The field isn't null, it has a FileObject in it that doesn't have a file.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Unless you set null=True as well, your database should complain if you tried to enter a blank value. If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None .
To do a not equal in Python Django queryset filtering, we can negate a equal with ~ . to call filter with the Q object negated with ~ to return all the Entry results that don't have id 3.
I was having this issue too, and finally found the solution!
no_files = MyModel.objects.filter(foo='')
This works because internally, the FileField
is represented as a local file path in a CharField
, and Django stores non-files as an empty string ''
in the database.
An alternative solution:
no_files = MyModel.objects.filter(foo__in=['',None])
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