【问题标题】:Django AngularJS JSONResponse view in rendering json output渲染 json 输出中的 Django AngularJS JSONResponse 视图
【发布时间】:2013-11-17 07:14:35
【问题描述】:

我正在使用 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 ..... 

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

【问题讨论】:

  • 跑题了,但compile真的有必要吗?

标签: python django angularjs jsonresponse


【解决方案1】:

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

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

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

如果没有,你应该在视图中将对象规范化为简单的python类型(dict、list、string..,json模块编码没有问题的那种)。所以改为:

'category':r.category

你可以这样做:

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

另外作为旁注:使用exec超级坏主意。不要在生产中使用它!

【讨论】:

    【解决方案2】:

    您应该为 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);
    

    你可以传递'param'对象:

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

    【讨论】:

      猜你喜欢
      • 2014-03-16
      • 2018-06-12
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 2020-04-02
      • 2015-02-04
      • 2018-12-13
      • 1970-01-01
      相关资源
      最近更新 更多