Home > Back-end >  How to filter objects in specific time range in Django
How to filter objects in specific time range in Django

Time:06-16

How do you guys filter objects within a specific time range including minutes?

So, I have a ticketing system, in which users report work time for specific tickets. I need to filter this data for a report. Currently, I'm using Q(time_to__hour__range=(9, 17)) which will select all objects from 9:00 till 17:59, but management needs this report to be till 18:05.

Here is a filter which I'm using currently:

f = Q(time_from__range=[form.cleaned_data.get('date_range_from'),
      form.cleaned_data.get('date_range_to')   timedelta(days=1)])\
    & Q(client__in=form.cleaned_data.get('client_set') if form.cleaned_data.get('client_set') else 
        Clients.objects.all())\
    & Q(tech__in=form.cleaned_data.get('tech_set') if form.cleaned_data.get('tech_set') else 
        Tech.objects.all())

if form.cleaned_data.get('selection') == '1':
    f &= Q(time_to__hour__range=(9, 17))
elif form.cleaned_data.get('selection') == '2':
    f &= ~Q(time_to__hour__range=(9, 17))

p.s. Django version 3.1.1

CodePudding user response:

One trick (depends on data size) is to get the data till 7pm (19:00) and filter the received data on python size to remove the extra record (after 18:05).

CodePudding user response:

Since you are already using Q objects, you can specify the extra minutes in hour 18 by or-ing in another Q object.

time_range = Q(time_to__hour__range=(9, 17)) | \
             Q(time_to__hour = 18, time_to__minute__range=(0,5) )
if form.cleaned_data.get('selection') == '1':
    f &= time_range
elif form.cleaned_data.get('selection') == '2':
    f &= ~time_range # I'm less certain here

I can't find the doc for the ~ operator on Q objects. I would have been building a queryset using .filter(time_range) to include and .exclude(time_range) to get precisely all the others.

  • Related