Answer the question
In order to leave comments, you need to log in
How to use JSONResponse?
In a Django application, you need to receive data from one model in the form of JSON. Of course, you can tie the django-rest-framework (there is experience with it), but since a full-fledged REST API is not needed, I want to do it using only django tools.
I'm using CBV, so I decided to attach the JSONResponseMixin from the manual to my DetailView. Stupidly copy-pasted. As a result: TypeError: blabla is not JSON serializable. I suspect that because of the ForeignKey that is in the model.
Found in copypasta:
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
Answer the question
In order to leave comments, you need to log in
Get a list of fields and give the necessary
ones The serializer in DRF just iterates over the described fields
I'm still a complete novice, but for my model I do something like this
#model
class CustomModel(model):
#some fields
def as_json(self):
return {
"id": self.id,
#other fields
}
objects = CustomModel.objects.filter(bla_bla_field = '1')
data = [ obj.as_json() for obj in objects]
return HttpResponse(json.dumps({"data": data}), content_type='application/json')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question