JGCW
JGCW

Reputation: 1529

Django Filter query - ignoring if the parameter is null

In my django APIView class, I am taking in month and year from a POST in the following way:

month = request_data.get("month")
year = request_data.get("year")

Then I am calling a query to get the data where the month == month and year == year.

queryset =  Expenses.objects.filter(month=month, year=year)

This totally works if I am posting the month and year. But I want to do the following:

If month is null, i want to get every record in the POST-ed year. At the moment if I POST month as null, then I don't get any results. I know this can be sorted by a simple if-else, but I want to know if there is any simpler way.

Upvotes: 2

Views: 1626

Answers (1)

Domen Blenkuš
Domen Blenkuš

Reputation: 2242

Have you considered this?

filters = {'year': request_data.get("year")}

month = request_data.get("month")
if month:
    filters['month'] = month

queryset =  Expenses.objects.filter(**filters)

Upvotes: 6

Related Questions