[Answer]-How to handle changing dates in Django Queries

1πŸ‘

βœ…

I’ve solved problems like this in the past by inverting the logic and using exclude, eg:

return Cleanedlog.objects.filter(dest_url__contains=self.kwargs["url_chunk"]) \
           .exclude(time_received__lt=from_date).exclude(time_received__gt=to_date)

And then take values and annotate and count as desired.

Comparisons against None always fail, so nothing gets excluded unless the date is provided.

That’s probably the simplest way to write it, but you can also take advantage of the ability to chain querysets without evaluating them:

base_qs = Cleanedlog.objects.filter(dest_url__contains=self.kwargs["url_chunk"])
if from_date is not None:
    base_qs = base_qs.filter(time_received_gte=from_date)
if to_date is not None:
    base_qs = base_qs.filter(time_received_lte=to_date)
return base_qs.values(# as above

That avoids putting the unnecessary None comparisons into the query at all.

Leave a comment