0

我有以下基于类的视图,当我发出 ajax 请求时,我收到“模块”对象不可调用错误 /?id=145

有任何想法吗 ?

class CityList(ListView):
    template_name = "profile/profile.html"
    model = City

    def render_to_response(self, context, **response_kwargs):

        if self.request.is_ajax() and self.request.GET.get('query'):
            query = self.request.GET.get('query')
            city_filter = [{'name': i.name,
                                'id': i.id}
                                for i in City.objects.filter(
                                name__icontains=query)]
            results = city_filter
            return HttpResponse(json.dumps(results),
                                mimetype='application/json')
        elif self.request.GET.get('id'):
            query = self.request.GET.get('id')
            if query:
                return HttpResponse(json.dumps(list(self.object_list.filter(
                    id=query).values('name', 'id')
                )), mimetype='application/json')
4

1 回答 1

0

data = serializers.serialize('json', self.object_list.filter(id=query))

完全解决了我的问题。我不确定为什么 json.dumps 没有工作,但序列化程序在下面的代码中像魅力一样工作。

  class CityList(ListView):
        template_name = "profile/profile.html"
        model = City

        def render_to_response(self, context, **response_kwargs):

            if self.request.is_ajax() and self.request.GET.get('query'):
                query = self.request.GET.get('query')
                city_filter = [{'name': i.name,
                                    'id': i.id}
                                    for i in City.objects.filter(
                                    name__icontains=query)]
                results = city_filter
                return HttpResponse(json.dumps(results),
                                    mimetype='application/json')
            if self.request.GET.get('id'):
                query = self.request.GET.get('id')
                if query:

                    data = serializers.serialize('json', self.object_list.filter(id=query))
                    return HttpResponse(data)
于 2013-09-16T08:04:11.247 回答