[英]Django AngularJS JSONResponse view in rendering json output
我正在使用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 .....
考慮到我可能做錯了什么。 如果有人有任何建議,請回答。
JSONResponse
可能正在使用標准的python json編碼器,該編碼器實際上並未為您編碼對象,而是輸出其字符串表示形式( repr
),因此輸出<Category: The New Category>
輸出。
您可能需要使用一些外部序列化程序類來處理django對象,例如:
如果不是,則應在視圖內部將對象規范化為簡單的python類型(dict,list,string ..,即json模塊編碼沒有問題的類型)。 所以改為:
'category':r.category
你可以做:
'category': {'name': r.category.name}
另外請注意:使用exec
是個壞主意 。 不要在生產中使用它!
您應該為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}});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.