I have a problem in django trying to exclude or include part of the filter if the parameter is null.
I have 4 parameters in my model:
StartDate, EndDate, Severity and Source.
The filter can have one or more of these parameters. If I pass 1 of them the others could be None
unless they are defined.
I was able to solve my problem with query raw by doing
WHERE (param IS NULL OR param=param)
and the same in django
"""SELECT * FROM mymanagelogs_logs WHERE (%(severity)s IS NULL OR severity=%(severity)s) AND (%(source)s IS NULL OR source=%(source)s) AND (%(start_date)s IS NULL OR timestamp >= %(start_date)s) AND (%(end_date)s IS NULL OR timestamp <= %(end_date)s)""",
params={'severity': severity, 'source': source, 'start_date':start, 'end_date':end}
)
but I can’t do the same QuerySet:
objects.filter(Q(date__range=(start, end)) & (Q(severity=severity) | Q(severity=None))
Any ideas?
2
Answers
You could try and build the queryset incrementally. For example:
__isnull is used to check for NULL data.
Also no need of using & for MYSQL ‘AND’ as filter checks using ‘AND’ by default.