Django Model过滤器,带关键字

时间:2016-02-19 15:31:19

标签: django django-models

我正在进行关键字搜索。

当用户输入关键字时,可能是' order_num'或' custom_name',

当我做filter(Q(order_num=keyword) | Q(custom_name=keyword))

它引发了一个Value错误。

因为order_num是一个int,而custom_name是一个str。

如何使用关键字进行此查询?

1 个答案:

答案 0 :(得分:1)

您可以使用int(keyword)转换搜索关键字,但由于用户可能会输入字符串,因此您需要区分:

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)

修改

即使有多个字段也是如此:

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