Overriding get_queryset () in Django DetailView

I have two models: City and State with the ForeignKey state for City.My CityDetailView url is built as:

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

My CityDetailView called by the above url:

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

My city model has unique names for each city. If I try to access a city that occurs in two states, I get an error that get () returned more than one City. I am trying to override the get_queryset () method to filter out only city models in one state, but it doesn't seem to work, which is odd because my CityListView is similar, but it works fine. Any thoughts on what I am missing will be appreciated.

+5
2

get_context_data, .

0

get_object DetailView.

- :

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
+7

All Articles