Cipher
Cipher

Reputation: 2122

Conditional Django Query

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)
)

Upvotes: 0

Views: 50

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29977

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.

Upvotes: 1

Related Questions