我有两个模型,City 和 State,State 是 City 的 ForeignKey 关系。我的 CityDetailView url 构造为:
r'^state/(?P<state>[-\w]+)/city/(?P<slug>[-\w]+)/$'
上述网址调用的我的 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() 方法以仅过滤掉单个状态下的 City 模型,但它似乎不起作用,这很奇怪,因为我的 CityListView 相似但工作正常。对我所缺少的任何想法将不胜感激。