0

我正在使用 python django 开发我的网站之一,我在其中一个页面中使用了 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'])

当我使用 AngularJS 返回时,在我的 HTML 代码中:

$scope.search = function(){
    $scope.results = $http.get("{% url 'search-requests-show' %}?term="+$scope.term).then(
        function(result){
            return result.data;
        }
    );
}

HTML 输出的结果在 {[{results}]} 中:

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

问题是我无法使用 results.category 访问,因为输出在“字符串”中,所以 ng-repeat="result in results" 将结果作为

[ { ' c a ..... 

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

4

2 回答 2

1

JSONResponse is probably using standard python json encoder, which doesn't really encode the object for you, instead it outputs a string representation (repr) of it, hence the <Category: The New Category> output.

You might need to use some external serializer class to handle django objects, like:

http://web.archive.org/web/20120414135953/http://www.traddicts.org/webdevelopment/flexible-and-simple-json-serialization-for-django

If not, you should then normalize object into simple python types inside the view (dict, list, string.., the kind that json module has no problem encoding). So instead doing:

'category':r.category

you could do:

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

Also as a sidenote: using exec is super bad idea. Don't use it in production!

于 2013-11-17T10:29:00.140 回答
0

您应该为 Angular 返回 json 字符串:

import json
def resource_view(request):
    # something to do here
    return HttpResponse(json.dumps(your_dictionary))

为了更好地使用,我推荐djangorestframework

无关:

$http.get("{% url 'search-requests-show' %}?term="+$scope.term);

您可以传递“参数”对象:

$http.get("{% url 'search-requests-show' %}", {param : {term:$scope.term}});
于 2013-11-17T10:00:52.947 回答