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.
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.
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.
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.
Exact is unnecessary here:
Something.objects.exclude(file='')
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)
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
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