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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With