如何在 Django 模型中返回对象数组

Mic*_*ell 1 python arrays django angularjs

我正在使用 javascript(加上 AngularJS 和 Restangular)来调用 Django 端点并检索一组提案。但我似乎无法正确理解我的 Django 语法。

How do I return and array of objects in a given Django model?

def proposal_api(request):
    response = {}
    response['proposal_list'] = Proposal.objects.all()
    return response
Run Code Online (Sandbox Code Playgroud)

The Django View above throws the following Attribute error: 'dict' object has no attribute 'status_code'

Once I receive the array of proposals from the above Django View (with IDs, names, questions, etc...) I'll use AngularJS to display everything.

pat*_*eet 7

You need to read up on writing views in the documentation. A view function should return an HTTP response object.

The simplest way would be to just use the HttpResponse object from Django like so

from django.core import serializers
from django.http import HttpResponse

def proposal_api(request):
    response = {}
    response['proposal_list'] = serializers.serialize("json", Proposal.objects.all())
    return HttpResponse(response, content_type="application/json")
Run Code Online (Sandbox Code Playgroud)

If you are building an API, however, I would strongly encourage you to checkout TastyPie or Django-Rest-Framework.