有这样一张桌子:
+---+----+-------+------+
| | id | color | type |
+---+----+-------+------+
| 1 | 1 | Blue | 2 |
+---+----+-------+------+
| 2 | 2 | Green | 4 |
+---+----+-------+------+
| 3 | 3 | White | 5 |
+---+----+-------+------+
| 4 | 4 | Red | 6 |
+---+----+-------+------+
| 5 | 5 | Gray | 8 |
+---+----+-------+------+
在模板中,该表中有两个字段可以进行搜索。一个用于搜索 color 的字段是一个字符串,另一个用于搜索 type 是一个数字。
在 views.py 中我有这个过滤器:
results = models.MyModel.objects.filter(Q(color__iexact=search_query) | Q(type=search_query))
如果我搜索一个数字,它会显示一些结果,而搜索一个字符串会导致如下错误:
<块引用>/search/ 处的值错误
字段 'id' 需要一个数字,但得到了 'White'。
我该怎么做才能纠正它?
答案 0 :(得分:2)
嗯,这是因为您的 type
字段是 int
而您正尝试使用 str
查询它,您应该做的是定义一个单独的 input 对于 type
字段,获取值然后查询:
color_search_query = request.POST.get('color_search_query')
id_search_query = request.POST.get('id_search_query')
results = models.MyModel.objects.all()
if color_search_query:
results = results.filter(color__iexact=color_search_query)
if id_search_query:
results = results.filter(type=id_search_query)