Anton Khodak
Anton Khodak

Reputation: 3696

Django ORM filter default value which returns all objects

I have a model Book which has a field year_of_publishing. A user inputs the year and I want to filter the Book's set getting all the books published in that year.

year = self.cleaned_data.get('year', SOME_DEFAULT_VALUE)
books = Book.objects.filter(year_of_publishing=year)

However the user might leave year field blank, and I want to put some default value, obtaining which in the .filter function Django ORM would return all the books like this filter was not present at all. What value should I use? I suppose it should be type independent, so I can use it for Char-, Choice- and other type of fields.

Upvotes: 4

Views: 1948

Answers (2)

Shang Wang
Shang Wang

Reputation: 25549

You can just build a queryset with a dictionary:

parameters = ['year', 'foo', 'bar']
query_dict = {}

for parameter in parameters:
    if self.cleaned_data.get(parameter, None):
        query_dict[parameter] = self.cleaned_data.get(parameter)

books = Book.objects.filter(**query_dict)

Upvotes: 6

Brandon Taylor
Brandon Taylor

Reputation: 34573

You can pass an empty dictionary to .filter() to return all results, or filter on the fields/values you want:

filters = {}

year = request.GET.get('year')
if year:
    filters['year'] = year

books = Book.objects.filter(**filters)

Upvotes: 7

Related Questions