Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset filter for blank FileField?

Tags:

python

django

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.

like image 332
MikeN Avatar asked Jan 23 '11 00:01

MikeN


People also ask

Can I filter a QuerySet Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How do I check if a field is empty in Django?

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 .

How do I do a not equal in Django QuerySet filtering?

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.


2 Answers

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.

like image 155
Andrew Avatar answered Sep 19 '22 19:09

Andrew


An alternative solution:

no_files = MyModel.objects.filter(foo__in=['',None]) 
like image 30
user1470687 Avatar answered Sep 20 '22 19:09

user1470687