如何在Django模型中返回对象数组 [英] How to Return an array of objects in a Django model

查看:142
本文介绍了如何在Django模型中返回对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用javascript(加上AngularJS和Restangular)来调用Django端点并检索提案数组.但是我似乎无法正确使用Django语法.

I'm using javascript (plus AngularJS and Restangular) to call a Django endpoint and retrieve an array of proposals. But I can't seem to get my Django syntax right.

如何在给定的Django模型中返回对象和对象数组?

def proposal_api(request):
    response = {}
    response['proposal_list'] = Proposal.objects.all()
    return response

上面的Django视图抛出以下属性错误:'dict'对象没有属性'status_code'

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

一旦我从上述Django视图中收到了一系列建议(带有ID,名称,问题等),我将使用AngularJS来显示所有内容.

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

推荐答案

您需要阅读

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

最简单的方法是像这样使用Django中的 HttpResponse 对象

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")

但是,如果您正在构建API,我强烈建议您检出 TastyPie Django-Rest-Framework .

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

这篇关于如何在Django模型中返回对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆