Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Model.Objects.all() to JSON in python using django

I have a list of objects of the same model type. I want to iterate over this list and create a JSON to send back. I tried some things like 2-dim arrays, google,... but can't find something like this? Though I think it can't be difficult.

my code now is:

def get_cashflows(request):

        response_data = {}
        cashflow_set = Cashflow.objects.all();
        i = 0;
        for e in cashflow_set.iterator():
            c = Cashflow(value=e.value, date=str(e.date));
            response_data[i] = c;

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

here it is not possible to give model in json.dumps. But how i give more then 1 object to it?

error :

TypeError: coercing to Unicode: need string or buffer, float found
[08/Sep/2016 14:14:00] "GET /getcashflow/ HTTP/1.1" 500 85775
like image 904
sg_sg94 Avatar asked Sep 08 '16 12:09

sg_sg94


People also ask

How do I return a model object in JSON Django?

To return a queryset of python object as JSON, we first have to convert it into a Python dictionary. The process of converting one data type to another is called serialization. We import the serialize function. This function accepts the following parameters: format, queryset, and an optional fields parameter.


1 Answers

this is how to do it in general:

#view: 
from django.core import serializers

def get modelAPI(request):
    SomeModel_json = serializers.serialize("json", SomeModel.objects.all())
    data = {"SomeModel_json": SomeModel_json}
    return JsonResponse(data)

for more you can see Django Documentation

like image 187
Gil Hadad Avatar answered Oct 04 '22 15:10

Gil Hadad