22

I am trying to make a json array in django but I am getting error -

In order to allow non-dict objects to be serialized set the safe parameter to False

and my views.py -

def wall_copy(request):
    if True:
        posts = user_post.objects.order_by('id')[:20].reverse()
        return JsonResponse(posts) 

Basically user_post is a model a posts is the object of top 20 saved data. I want to send a json array but I am unable to convert posts into a json array. I also tried serializers but it didnt helped.

I am stuck help me please.

Thanks in advance.

3 Answers 3

48

Would this solve your problem?

from django.core import serializers
def wall_copy(request):
    posts = user_post.objects.all().order_by('id')[:20].reverse()
    posts_serialized = serializers.serialize('json', posts)
    return JsonResponse(posts_serialized, safe=False) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked but now I am unable to get the data. Can you please tell me how can I retrieve the json data...??
Sorry there was a mistake n the posts=... line. The call to the all() function was missing. Does it work for you now?
8

You can solve this by using safe=False:

    def wall_copy(request):
        posts = user_post.objects.all().order_by('id')[:20].reverse()

        return JsonResponse(posts, safe=False)

Note that it's not really unsafe - you just have to make sure on your own, that what you are trying to return can be converted to JSON.

See JsonResponse docs for reference.

Comments

0

Try to use values method: http://django.readthedocs.org/en/1.7.x/ref/models/querysets.html#django.db.models.query.QuerySet.values. It will produce dict-like representation for objects fields you need.

1 Comment

Hey I tried it but it did not worked for me. Anyways thanks for the advice, that was something new.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.