0

I am using this query for search. I want to search list according to status, start_date and end_date

status can be Active, Inactive, or AllStatus.

start_date can be date or None(can be empty)

end_date can be date or None(can be empty)

status = form.cleaned_data['status']
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']

I made this below query but it is giving me error - Cannot use None as a query value.

Can any tell me whats the problem and how should i query using status, start_date and end_date with sometimes value as None

Jobs.objects.filter(
    Q(job_company=self.request.user.userprofile.user_company) |
    Q(job_created_on__range=[start_date, end_date]) |
    Q(job_created_on__gt=start_date) |
    Q(job_created_on__lt=end_date) |
    Q(job_status=status)
)
Cipher
  • 2,060
  • 3
  • 30
  • 58

1 Answers1

1

You can build the lookup dynamically:

status = form.cleaned_data['status']
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
company = self.request.user.userprofile.user_company

lookups = (Q(job_company=company) |  Q(job_status=status) 

if start_date:
    lookups = lookups | Q(job_created_on__gt=start_date)
if end_date:
    lookups = lookups | Q(job_created_on__lt=end_date)

Jobs.objects.filter(lookups)

The job_created_on__range lookup is unnecessary.

Also, check if you really want job_created_on__gt/__lt or job_created_on__gte/__lte.

Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75
  • Sir it is giving me error `received a naive datetime (2019-01-12 00:00:00) while time zone support is active RuntimeWarning` and even Query is not working – Cipher Jan 17 '19 at 12:37
  • That is most likely an issue with your form and probably best answered in a separate question. Also, no need to call me sir, we are all friends here :) – Daniel Hepper Jan 17 '19 at 12:40
  • Because your datetime expects tzinfo (Time Zone Information) do this. `from django.utils.timezone import make_aware` and `make_aware(start_date)` `make_aware(end_date)` @HuzaifSayyed – Yugandhar Chaudhari Jan 17 '19 at 17:31
  • @YugandharChaudhari `start/end_date` are actually `date` object, see this question & answer: https://stackoverflow.com/questions/54237576/runtimewarning-for-datefield-in-django/54238093#54238093 – Daniel Hepper Jan 17 '19 at 19:14