En Xie
En Xie

Reputation: 626

Django Model filter with keyword

I am doing a keyword search.

when user enter a keyword, it could be 'order_num' or 'custom_name',

when I do filter(Q(order_num=keyword) | Q(custom_name=keyword))

it raise a Value error.

because the order_num is a int, and custom_name is a str.

how to make this query with keyword ?

Upvotes: 2

Views: 1092

Answers (1)

Shang Wang
Shang Wang

Reputation: 25559

You could use int(keyword) to convert the search keyword, but since user might input string, you need to distinguish that:

try:
    result = Model.objects.filter(Q(order_num=int(keyword)) |
                                  Q(custom_name=keyword))
except ValueError:
    # no point to filter order_num because it's not a number anyway
    result = Model.objects.filter(custom_name=keyword)

Edit:

Even if there are multiple fields it would be the same:

# create an empty Q() object to start with
query = Q()

try:
    int_keyword = int(keyword)
    query |= Q(order_num=int_keyword)
    query |= Q(another_int_field=int_keyword)
except ValueError:
    pass
# the string query would always be executed
query |= Q(custom_name=keyword)
query |= Q(other_field=keyword)

results = Model.objects.filter(query)

Upvotes: 4

Related Questions