覆盖Django DetailView中的get_queryset()

时间:2011-06-18 23:02:24

标签: django-views django-class-based-views

我有两个模型,City和State,State是CityK的ForeignKey关系。我的CityDetailView url构造如下:

r'^state/(?P<state>[-\w]+)/city/(?P<slug>[-\w]+)/$'

上面url调用的CityDetailView是:

class CityDetailView(DetailView):
    model = City
    context_object_name = 'city'
    template_name = 'location/city_detail.html'

    def get_queryset(self):
        state = get_object_or_404(State, slug__iexact=self.kwargs['state'])
        return City.objects.filter(state=state)

    def get_context_data(self, **kwargs):
        context = super(CityDetailView, self).get_context_data(**kwargs)
        city = City.objects.get(slug__iexact=self.kwargs['slug'])
        context['guide_list'] = Guide.objects.filter(location=city).annotate(Count('review'), Avg('review__rating'))
        return context

我的城市模型为每个城市都有唯一的名称。如果我尝试访问一个发生在两个州的城市,我会收到一个错误,即get()返回了多个城市。我试图覆盖get_queryset()方法只过滤掉单个状态的城市模型,但它似乎没有工作,这是奇怪的,因为我的CityListView相似,但工作正常。任何关于我失踪的想法都会受到赞赏。

2 个答案:

答案 0 :(得分:10)

您需要覆盖DetailView中的方法get_object才能执行此操作。

这样的事情应该做:

class CityDetailView(DetailView):
    model = City
    context_object_name = 'city'
    template_name = 'location/city_detail.html'

    def get_object(self):
        state = get_object_or_404(State, slug__iexact=self.kwargs['state'])
        return self.model.objects.filter(state=state)

    def get_context_data(self, **kwargs):
        context = super(CityDetailView, self).get_context_data(**kwargs)
        cities = self.object
        context['guide_list'] = Guide.objects.filter(location=cities).annotate(Count('review'), Avg('review__rating'))
        return context

答案 1 :(得分:1)

我在get_context_data函数上收到错误,因为我没有在那里过滤城市列表而不是主视图对象。