Django ValueError问题求助:Field 'id'期望数字却获字符串'news1'
解决 ValueError: Field 'id' expected a number but got 'news1' 的问题
这个错误的根源其实很直观——你在BlogDetailView里犯了个小逻辑错误:
URL传递过来的slug是字符串格式(比如news1),但你查询博客时用了Blog.objects.get(id=slug),而Django模型默认的id字段是整数类型主键,系统尝试把字符串转成整数失败,就抛出了这个类型不匹配的错误。
好在你的代码其实已经准备好了正确的解决方案:Blog模型里已经定义了url字段(SlugField,专门用来存储这种字符串式的路径标识),而且get_absolute_url方法也是基于这个字段生成的跳转链接。
只需要修改BlogDetailView里的查询条件就行,具体步骤:
- 修正视图中的查询逻辑,把匹配
id改成匹配url字段:
class BlogDetailView (View): def get(self, request, slug): # 将 id=slug 替换为 url=slug posts = Blog.objects.get(url=slug) return render(request, "home/blog-detail.html", {"posts": posts})
- (可选但推荐)为了让代码更健壮,用
get_object_or_404替代直接get(),这样当找不到对应slug的博客时,会返回友好的404页面,而不是服务器500错误:
# 确保已经导入这个方法 from django.shortcuts import get_object_or_404 class BlogDetailView (View): def get(self, request, slug): posts = get_object_or_404(Blog, url=slug) return render(request, "home/blog-detail.html", {"posts": posts})
这样修改后,Django就会用URL中的字符串slug去匹配Blog模型的url字段(本身就是字符串类型),不会再出现类型转换的错误,同时也提升了代码的容错性。
内容的提问来源于stack exchange,提问作者Алексей Синельник
相关产品推荐
相关产品推荐

