1👍
The code you shared assumes JSONResponse
will serialize an ORM object, but according to Django documentation, it won’t:
https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects
https://docs.djangoproject.com/en/3.0/topics/serialization/#djangojsonencoder
It will work if you serialize the Django ORM object before passing it to JSONResponse
Consider doing the following:
from django.core import serializers
data = serializers.serialize("json", MyModel.objects.all())
https://docs.djangoproject.com/en/3.0/topics/serialization/
django-rest-framework is a very popular lib used in scenarios like the one you shared
https://docs.djangoproject.com/en/3.0/topics/serialization/#djangojsonencoder
0👍
what about this:
def get_all_models(request):
return JsonResponse({"models": list(MyModel.objects.all().values())},safe=False)
the point is here:
MyModel.objects.all().values()
safe=False
Source:stackexchange.com