[Fixed]-Convert Model.Objects.all() to JSON in python using django


this is how to do it in general:

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


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:

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),

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


Also to note:

you could use the queryset directly serializers.serialize("json", Cashflow.objects.all())

and you’re also not incrementing i in your loop…


This is a project that it can serialize(JSON base now) all data in your model and put them to a specific directory automatically and then it can deserialize it whenever you want… I’ve personally serialized thousand records with this script and then load all of them back to another database without any losing data.

Anyone that would be interested in opensource projects can contribute this project and add more feature to it.


Leave a comment