[Answered ]-How to create Django custom query?

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

๐Ÿ‘คlaffuste

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)
๐Ÿ‘คRafael

0๐Ÿ‘

I would do something like that

if name and number:
    UserInfo.object.filter(name='John',number='1234')
๐Ÿ‘คcor

0๐Ÿ‘

The solution according to your example isโ€ฆ

MatchedUsers = UserInfo.object.filter(name='John',number='1234')
return MatchedUsers
๐Ÿ‘คPawan

Leave a comment