S
S
Stanislav Fateev2015-07-02 17:14:13
Django
Stanislav Fateev, 2015-07-02 17:14:13

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.

What needs to be done to correctly serialize the model?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Serge K, 2015-07-02
@svfat

Get a list of fields and give the necessary
ones The serializer in DRF just iterates over the described fields

D
dovgalmichael, 2015-07-03
@dovgalmichael

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
        }

and then the challenge.
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')

I think that the general meaning is clear and this option, if suitable, can be redone for yourself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question