Apostolos
Apostolos

Reputation: 8111

Queries with and in django depending on form data

I would like to create a query that takes the data posted from a form as search creteria and filters the models according to those creteria. Example

<form>
    <first_name input>
    <middle_name input>
    <last_name input>        
</form>

My wanted behavour is the view to match with end all queries but only if they have a value. That is if user only complets the first name input to search only using the first name, if middle name was given to then to search using both creteria etc. My idea is to do this manually but it doesn't sound so good.

if first_name != '' and middle_name='' and last_name='':
    return filtering only with name
elif etc....

It isn't constructive or correct. Is there another way to do this in django?To use a creteria only if it isn't empty string that is.

Upvotes: 0

Views: 37

Answers (2)

Apostolos
Apostolos

Reputation: 8111

My solution was the following, but please tell me if it's right.

model.objects.filter(
                     Q(first_name__icontains=fist_name) &
                     Q(middle_name__icontains=middle_name) &
                     Q(last_name__icontains=last_name)
                    )

since if the post data is empty string it will match all, but if any of the others is not an empty string it will filter those results by that creteria. So

e.g

first_name=''
last_name = 'Jones'
middle_name='Paul'

then

first_name matches all
but it extracts only thouse who their middle name is Paul and last name Jones
ergo John Paul Jones

:P Does this way cost more in database transactions time?

Upvotes: 0

mariodev
mariodev

Reputation: 15559

The code flow can look like this:

kwargs = {}

if first_name != '':
    kwargs.update({'first_name': "Foo"})
if middle_name != '':
    kwargs.update({'middle_name': "Bar"})

etc...

MyModel.objects.filter(**kwargs)

Upvotes: 2

Related Questions