Convert Model.Objects.all() to JSON in python using django
<p>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. </p>

<p>my code now is:</p>

<pre><code>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"
        )
</code></pre>

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

<p>error : </p>

<pre><code>TypeError: coercing to Unicode: need string or buffer, float found
[08/Sep/2016 14:14:00] "GET /getcashflow/ HTTP/1.1" 500 85775
</code></pre>

<p>As @Ivan mentions the DRF does this out of the box if you want an API layer, but if you just want a basic view to return some json without the overhead of configuring a new package then it should be a fairly simple operation with django's serializers:</p>

<pre><code>from django.core import serializers

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(
        serializers.serialize("json", response_data),
        content_type="application/json"
    )
</code></pre>

<p>The docs have a good break down of how to achieve this even if the default json serializer doesn't quite do what you need</p>

<p><a href="https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-formats-json" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-formats-json</a></p>

<p>Also to note: </p>

<p>you could use the queryset directly <code>serializers.serialize("json", Cashflow.objects.all())</code></p>

<p>and you're also not incrementing <code>i</code> in your loop...</p>

python json django