[Django]-Django queryset filter filefield not empty

31👍

Exact is unnecessary here:

Something.objects.exclude(file='')

10👍

There are better options, I think:

from django.db.models import Q    

Something.objects.filter(~Q(file__isnull=True))

or

Something.objects.exclude(file__isnull=True)
👤simP

7👍

This worked perfectly for me:

objects = MyModel.objects.exclude(
    Q(file='')|Q(file=None)
)

https://books.agiliq.com/projects/django-orm-cookbook/en/latest/filefield.html

👤daaawx

1👍

I think we can directly filter out null values using:

Something.objects.filter(file__isnull=False)

In filter, you can give multiple values but in the exclude clause, you can’t give multiple values. you must have to use chaining with exclude.

for more details of Django filter and exclude you can refer this link

0👍

Your field allows nulls, so I guess the ones without files have the field as null, not the empty string. Try this:

Something.objects.exclude(file=None)

Leave a comment