[Fixed]-Importing data to a particular model

1๐Ÿ‘

โœ…

As I see this question may relate to another (mentioned in comments) , but for this particular caseโ€ฆ

As you are using DjangoRestFramework (the right way), to get all data in Json format you may:

in 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

next in shell (views in future):

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

UPDATE in urls.py:

urlpatterns = [
    ...
    url(r'my/', my),
    ...
]

add in 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  )
๐Ÿ‘ค1844144

Leave a comment