Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset filter filefield not empty

I'm trying to filter a queryset, to exclude the one with no file. And I can't get it work, except by numberless iterations.

class Something(models.Model):
    name = models.CharField(max_length=512)
    file = models.FieldField(upload_to="files", null=True, blank=True)

Then, to get the one with a file

 # this give me all objects
 Something.objects.exclude(file__exact='')
 
 # this is a valid solution, but hell, something easier should exist, 
 something_with_files = set()
 for s in Something.objects.all():
    if s.file:
        something_with_files.add(s)

What is the real solution to this?

PS: working on PostGres, I don't know if that can change anything at that point.

like image 766
Spoutnik16 Avatar asked Mar 16 '15 09:03

Spoutnik16


People also ask

Can I filter a QuerySet Django?

With the Django QuerySet class, you can apply filters that return QuerySets defined by your filters. The filter() method returns all objects that match the keyword arguments given to the method.

How check field is null in Django?

null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.


3 Answers

Exact is unnecessary here:

Something.objects.exclude(file='')
like image 180
Eugene Soldatov Avatar answered Sep 28 '22 02:09

Eugene Soldatov


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)
like image 30
simP Avatar answered Sep 28 '22 03:09

simP


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

like image 29
daaawx Avatar answered Sep 28 '22 02:09

daaawx