Python 呈现json输出时的Django AngularJS JSONResponse视图

Python 呈现json输出时的Django AngularJS JSONResponse视图,python,django,angularjs,jsonresponse,Python,Django,Angularjs,Jsonresponse,我正在用PythonDjango开发我的一个站点,我在我的一个页面中使用angularjs,在那里我给了用户搜索选项(特定请求)。这是我的模型 class Request(models.Model): description = models.TextField(blank=True,null=True) category = models.ForeignKey(Category) sub_category = models.ForeignKey(SubCategory)

我正在用PythonDjango开发我的一个站点,我在我的一个页面中使用angularjs,在那里我给了用户搜索选项(特定请求)。这是我的模型

class Request(models.Model):
    description = models.TextField(blank=True,null=True)
    category = models.ForeignKey(Category)
    sub_category = models.ForeignKey(SubCategory)
在我看来,我通过以下代码返回:

def some(code, x):
    exec code
    return x

def search_request(request):
    page = request.GET.get('page')
    term = request.GET.get('term')
    i = 0

    terms = "x = Request.objects.filter("
    for t in term.split(" "):
        i=i+1
        if(len(term.split(" "))>i):
            terms = terms +"Q(name__icontains='"+t+"')|"
        else:
            terms = terms +"Q(name__icontains='"+t+"'))"

    junk = compile(terms,'<string>', 'exec')

    spit = Request.objects.filter(name__icontains=term)
    requests = some(junk,spit)

    output = HttpResponse()
    output['values']=[{'requests':r,'category':r.category,'subcategory':r.sub_category} for r in requests]
    return JSONResponse(output['values'])
HTML输出的结果如{[{results}]}所示:

"[{'category': <Category: The New Category>, 'requests': <Request: Need a Table>, 'subcategory': <SubCategory: Testsdfsdfsad>}]"

看来我可能做错了什么。如果有人有任何建议,请回答。

您应该返回json字符串,用于:

import json
def resource_view(request):
    # something to do here
    return HttpResponse(json.dumps(your_dictionary))
为了更好的使用,我推荐

离题:

$http.get("{% url 'search-requests-show' %}?term="+$scope.term);
您可以传递“param”对象:

$http.get("{% url 'search-requests-show' %}", {param : {term:$scope.term}});

JSONResponse
可能正在使用标准的python json编码器,它并没有真正为您编码对象,而是输出对象的字符串表示(
repr
),因此输出

您可能需要使用一些外部序列化程序类来处理django对象,如:

否则,您应该在视图中将对象规范化为简单的python类型(dict、list、string..,json模块编码时没有问题的类型)。因此,我们应该:

'category':r.category
你可以做:

'category': {'name': r.category.name}

另请注意:使用
exec
是一个非常糟糕的主意。不要在生产中使用它

离题了,但是
编译
真的有必要吗?
'category':r.category
'category': {'name': r.category.name}