我从Order
对象的实例开始,并尝试将它们转换为JSON格式,这将用于更新表。我是特定于Django的代码构造的新手。
我选择的方法是:
Order
实例Order
个实例转换为中间Table
对象(格式已赋予)Table
对象序列化为JSON 到目前为止我走得很远,但除了在Python shell中运行之外,我无法运行整个应用程序。我已经有了模型和序列化器。
有人可以提供他的帮助,如何一次标记所有Order
个实例,并在一次API调用中将它们转换为Table
以及此简单示例中缺少的任何其他内容吗?
models.py:
# Order corresponds to Line in the Table
class Order(models.Model):
doc = models.CharField(max_length=200, blank=True, null=True)
order = models.CharField(max_length=200, blank=True, null=True)
nothing = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.order
class Table(models.Model):
pass
class Column(models.Model):
data = models.CharField(max_length=200, blank=True, null=True)
table = models.ForeignKey(Table)
def __str__(self):
return self.data
class Line(models.Model):
doc = models.CharField(max_length=200, blank=True, null=True)
order = models.CharField(max_length=200, blank=True, null=True)
nothing = models.CharField(max_length=200, blank=True, null=True)
table = models.ForeignKey(Table)
def __str__(self):
return self.order
serializers.py:
class TableSerializer(serializers.ModelSerializer):
columns = ColumnSerializer(many=True)
lines = LineSerializer(many=True)
class Meta:
model = Table
fields = [
'columns',
'lines'
]
class ColumnSerializer(serializers.ModelSerializer):
class Meta:
model = Column
fields = [
'data'
]
class LineSerializer(serializers.ModelSerializer):
class Meta:
model = Line
fields = [
'doc',
'order',
'nothing'
]
对于此关系数据:
doc order nothing
564251422 564210 5648
546546545 98745 4668
JSON输出应为:
{
"columns": [
{
"data": "doc"
},
{
"data": "order"
},
{
"data": "nothing"
}
],
"lines": [
{
"doc": "564251422",
"nothing": 0.0,
"order": "56421"
},
{
"doc": "546546545",
"nothing": 0.0,
"order": "98745"
}
]
}
Shell命令:
import polls.models
polls.models.Order.objects.all() # outputs all orders
table = polls.models.Table()
polls.models.Column(data="doc",table=table)
polls.models.Column(data="order",table=table)
polls.models.Column(data="nothing",table=table)
polls.models.Line(doc="564251422",order="56421",nothing="0.0",table=table)
polls.models.Line(doc="546546545",order="98745",nothing="0.0",table=table)
views.py(更新):
bunch = OrderSerializer(Order.objects.all(), many=True)
headers = bunch.data[0].keys()
headers_prepared = map (lambda x: {'data': x} , headers)
ordered_all = ( ('columns', headers_prepared), ('lines', bunch.data) )
data = collections.OrderedDict(ordered_all)
data_json = JSONRenderer().render(data)
return JsonResponse(data_json, safe=False)
答案 0 :(得分:1)
我认为这个问题可能与另一个问题有关(在评论中提到),但对于这个特殊情况......
当您使用DjangoRestFramework(正确的方式)时,要获得Json格式的所有数据,您可以:
serialisers.py中的:
from rest_framework import serializers
from polls.models import Order
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = ('doc', 'order', 'nothing')
# note we do not use other serializers
下一个 shell (将来的视图):
from rest_framework.renderers import JSONRenderer
from polls.models import Order
from polls.serializers import OrderSerializer
bunch = OrderSerializer(Order.objects.all(), many=True)
#this will output "lines" part of desired output
JSONRenderer().render(bunch.data)
#next to get columns, or i say headers
headers = bunch.data[0].keys()
# headers = ['doc','order','nothing']
# !note will fail if bunch.data is empty
headers_prepared = map (lambda x: {'data': x} , headers)
# headers_prepared = [{'data': 'doc'}, {'data': 'order'}, {'data': 'nothing'}]
import collections # need to use OrderedDict to store in our sequence
ordered_all = ( ('columns', headers_prepared), ('lines', bunch.data) )
#finally desired output
JSONRenderer().render( collections.OrderedDict(ordered_all) )
#all code and output tested on my dummy data
urls.py中的更新:
urlpatterns = [
...
url(r'my/', my),
...
]
添加views.py:
#as you sileny JSONResponse (from RestFramework docs) - need to show it
from django.http import HttpResponse
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
#now our view
import collections
def my(request):
bunch = OrderSerializer(Order.objects.all(), many=True)
# to get headers independent of presence of orders
empty = OrderSerializer()
headers = empty.data.keys()
headers_prepared = map (lambda x: {'data': x} , headers)
ordered_all = ( ('columns', headers_prepared), ('lines', bunch.data) )
out = collections.OrderedDict(ordered_all)
#finally desired output
return JSONResponse( out )