MiniGunnR
MiniGunnR

Reputation: 5800

How to create Django custom query?

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. :-/

Upvotes: 1

Views: 159

Answers (4)

Rafael
Rafael

Reputation: 2178

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)

Upvotes: 1

laffuste
laffuste

Reputation: 17085

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

Upvotes: 1

cor
cor

Reputation: 3393

I would do something like that

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

Upvotes: 0

Pawan
Pawan

Reputation: 4409

The solution according to your example is...

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

Upvotes: 0

Related Questions