【问题标题】:Dajngo- Error Field 'id' expected a number but got stringDjango-错误字段'id'需要一个数字但得到字符串
【发布时间】:2021-04-23 15:35:48
【问题描述】:

有一张这样的表:

+---+----+-------+------+
|   | 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/处的ValueError

字段“id”需要一个数字,但得到了“白色”。

我应该怎么做才能纠正它?

【问题讨论】:

  • 请显示完整代码。视图、形式和模型
  • 表格里可能有东西

标签: django django-views django-templates


【解决方案1】:

这是因为您的type 字段是int,而您正尝试使用str 查询它,您应该为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)

【讨论】:

  • 谢谢。你的答案是正确的,你的方法效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
  • 2023-02-06
  • 2022-01-12
  • 2021-08-31
相关资源
最近更新 更多