Django项目出现Improperly Configured错误:提示模型缺少QuerySet
解决Django ListView的Improperly Configured(缺少QuerySet)错误
嘿,我一眼就定位到问题啦!你遇到的这个ImproperlyConfigured错误,核心原因是Django ListView类视图的属性名大小写写错了。
问题根源
Django的ListView类要求用来指定数据集的属性名是小写的queryset,但你在三个视图类(RestaurantList、SpicyList、AsianList)里都写成了大写S的querySet。Python是大小写敏感的语言,Django无法识别这个错误的属性名,自然就会抛出“模型缺少QuerySet”的报错——而且只有访问关联restaurants的URL时才触发,其他URL用的是普通TemplateView,不受影响。
修复后的views.py代码
把所有的querySet改成queryset即可:
import random from django.shortcuts import render from django.http import HttpResponse from django.views import View from django.views.generic import TemplateView from django.views.generic.list import ListView class RestaurantList(ListView): queryset = Restaurant.objects.all() # 修正为小写的queryset template_name = 'restaurants/restaurants_list.html' class SpicyList(ListView): template_name = 'restaurants/restaurants_list.html' queryset = Restaurant.objects.filter(category__iexact='spicy') # 同样修改 class AsianList(ListView): template_name = 'restaurants/restaurants_list.html' queryset = Restaurant.objects.filter(category__iexact='asian') # 同样修改
额外小提示
除了修改属性名,你也可以通过重写get_queryset()方法来实现相同的效果,这种方式在需要动态生成数据集时更灵活:
class SpicyList(ListView): template_name = 'restaurants/restaurants_list.html' def get_queryset(self): return Restaurant.objects.filter(category__iexact='spicy')
修改完成后重启Django服务,再访问/restaurants/、/restaurants/asian/、/restaurants/spicy/这些URL,错误就会消失啦!
内容的提问来源于stack exchange,提问作者Duck Dodgers
相关产品推荐
相关产品推荐

