1

I have a model named UserInfo with the following fields: id, name, number

I want to create a custom search page. This will have the following elements: Search Box, Search Button Text field to match NAME Text field to match NUMBER

How it should work: Let's say I input 'John' as the name and '1234' as the number in the respective text boxes and click search. The result should show me the entries which has 'John' as the name and '1234' as the number.

The query is something like the following I guess: UserInfo.objects.filter(name='John').filter(number='1234')

I have made this kind of queries in PHP before, but that doesn't work in Django. I want to know what code can I use to associate multiple FILTERS in a query so that if there is data input in both name and number text boxes I get a query like the above but if I search for name only then the query becomes: UserInfo.object.filter(name='John') instead of

UserInfo.object.filter(name='John').filter(number='')

There should be an easy solution for this, I dunno. Very confused. :-/

4 Answers 4

1

Filter methods are chainable, immutable :)

def search_user(name=None, number=None):

    # Uncomment the following lines to return NO records when no input.
    # if not name and not number:
    #    return  UserInfo.objects.none()

    qs = UserInfo.objects.all()
    if name:
        qs = qs.filter(name=name)
    if number:
        qs = qs.filter(number=number)
    return qs

This example would return all records if no input.

(Note that QS are lazy, and all() would not retrieve all records unless accessed later on.)

Sign up to request clarification or add additional context in comments.

2 Comments

This looks like what I'm looking for. Thanks a lot. I'll give this a try. However, I don't understand what you mean by the sentence in brackets. :-/
You will understand what ladduste meant by reading this: docs.djangoproject.com/en/dev/topics/db/queries/… :)
1

Q is a powerful feature in Django. see Q class

from django.db.models import Q

# you cand do a lot of crazy things here 
query = Q(name__iexact=name) & Q(number=number)

users =  UserInfo.object.filter(query)

Comments

0

The solution according to your example is...

MatchedUsers = UserInfo.object.filter(name='John',number='1234')
return MatchedUsers

Comments

0

I would do something like that

if name and number:
    UserInfo.object.filter(name='John',number='1234')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.