开发者

Overriding get_queryset() in a Django DetailView

I have two models, City and State with State being a ForeignKey relation of City.My CityDetailView url is constructed as:

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

My CityDetailView called by the above url is:

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 and access a city that occurs in two states I get an error that the get() returned more than one City. I am trying to override the get_queryset() method to filter out only the City models in a single state but it does not seem to be working which is odd because my CityListView is similar but works fine. Any thoughts on what I am missing would be appreciated.


You need to override the method get_object in DetailView to do this.

Something like this should do:

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


I was getting the error on the get_context_data function because I was not filtering the city list there not on the primary view object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜