Django:为Rest-API创建JSON [英] Django : Create a JSON for Rest-API
问题描述
我想创建下表的json数据.该表具有两个字段名称和ID.我想创建=>
I want to create json data of following table. This table has two field Name and ID. I want to create the JSON data like =>
{"Instances": [{"Name": "test2", "ID":"7a3a2eab-7d3b-498b-bc69-ba39396ada4f"},{"Name": "test1", "ID":"1114cb76-f3df-4c60-8b12-5ad14224ffbd"}]}
Name ID
test2 7a3a2eab-7d3b-498b-bc69-ba39396ada4f
test1 1114cb76-f3df-4c60-8b12-5ad14224ffbd
ce-2 8b97b82b-a9e4-4fe0-adcb-eeaaac170301
ce-1 afaa50ad-8025-415b-81c4-566c8e06f388
我正在从api.nova.server_list(self.request)
获取以上数据.我试图编写以下代码以将数据转换为python + django中的json数据,但未成功.
I am getting the above data from api.nova.server_list(self.request)
. I tried to write following code to convert data into json data in python+django, but didn't succeeded.
class InstanceList(django.views.generic.View):
def get(self, request, *args, **kwargs):
instances=api.nova.server_list(self.request)
def serializer(m):
ret= {}
ret['Name']= m.name
ret['Id']=m.id
context= {
'instances': [serializer(m) for m in instances],
}
return HttpResponse(json.dumps(context), content_type='application/json')
推荐答案
我强烈建议您查看以下资源,以便在Django中创建REST API:
I would highly encourage you to look at these resources for creating a REST API in Django:
Django Rest Framework: http://www.django-rest-framework.org/
Django Rest Framework: http://www.django-rest-framework.org/
Tastypie API: http://tastypieapi.org/
Tastypie API: http://tastypieapi.org/
我个人已经成功地使用了Deliciouspie来创建一个REST API,以从模型返回JSON数据.这是开始使用的Tastypie文档的链接: https://django-tastypie.readthedocs. org/en/latest/
I have personally used Tastypie successfully to create a REST API returning JSON data from models. Here is a link to the Tastypie documentation to get started: https://django-tastypie.readthedocs.org/en/latest/
这篇关于Django:为Rest-API创建JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!