Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON Response in Django with Model

I am having some issue here. I am trying to return a JSON response made of a message and a model instance:

   class MachineModel(models.Model):
       name = models.CharField(max_length=64, blank=False)
       description = models.CharField(max_length=64, blank=False)
       manufacturer = models.ForeignKey(Manufacturer)
       added_by = models.ForeignKey(User, related_name='%(app_label)s_%(class)s_added_by')
       creation_date = models.DateTimeField(auto_now_add=True)
       last_modified = models.DateTimeField(auto_now=True)

    machine_model_model = form.save(commit=False)
    r_user = request.user.userprofile
    machine_model_model.manufacturer_id = manuf_id
    machine_model_model.added_by_id = request.user.id
    machine_model_model.save()
    alert_message = " The'%s' model " % machine_model_model.name
    alert_message += ("for '%s' " % machine_model_model.manufacturer)
    alert_message += "was was successfully created!"
    test = simplejson.dumps(list(machine_model_model))
    data = [{'message': alert_message, 'model': test}]
    response = JSONResponse(data, {}, 'application/json')


class JSONResponse(HttpResponse):
"""JSON response class."""
    def __init__(self, obj='', json_opts={}, mimetype="application/json", *args, **kwargs):
        content = simplejson.dumps(obj, **json_opts)
        super(JSONResponse,self).__init__(content, mimetype, *args, **kwargs)

But I keep getting:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")

TypeError: <MachineModel: "Test12"> is not JSON serializable

Why is that? I have seen before:

models = Model.objects.filter(manufacturer_id=m_id)
json = simplejson.dumps(models)

and that works... what is the difference?!

Thanks!

like image 401
abisson Avatar asked Sep 23 '12 15:09

abisson


People also ask

How do I return a JSON response in Django?

Returning a JSON response from a Django Model. 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.

What does JSON response do in Django?

Django JsonResponse JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data , should be a dict instance.

How do I return a JSON response?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.


2 Answers

You should use django serializers instead of simplejson:

For example, this returns correctly serialized data:

from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', some_queryset)
# serialize object
serialized_object = serializers.serialize('json', [some_object,])
like image 195
Serhii Holinei Avatar answered Sep 19 '22 17:09

Serhii Holinei


Method-1: Use Django's python serializer

I think this answer won't return a JSON or a Python dict/list object. So, use the format python instead of json

from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('python', some_queryset)
# serialize object
serialized_object = serializers.serialize('python', [some_object,])

Django shell response

In [2]: from django.core import serializers                                                                                                                             

In [3]: qs = SomeModel.objects.all()                                                                                                                                    

In [4]: json_res = serializers.serialize('json',qs)                                                                                                                     

In [5]: type(json_res)                                                                                                                                                  
Out[5]: str

In [6]: python_res = serializers.serialize('python',qs)                                                                                                                 

In [7]: type(python_res)                                                                                                                                                
Out[7]: list
#views.py
from django.core import serializers
from django.http.response import JsonResponse


def some_view(request):
    some_queryset = SomeModel.objects.all()
    serialized_queryset = serializers.serialize('python', some_queryset)
    return JsonResponse(serialized_queryset, safe=False)

Method-2: Use Django's values() method

The direct use of values() method will throw TypeError exception, so convert the QuerySet to a python list as below,

from django.http.response import JsonResponse


def sample_view(request):
    return JsonResponse(list(SomeModel.objects.all().values()), safe=False)
like image 20
JPG Avatar answered Sep 21 '22 17:09

JPG