Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating json array in django

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.

like image 994
aquaman Avatar asked Feb 26 '15 10:02

aquaman


2 Answers

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) 
like image 140
ger.s.brett Avatar answered Nov 07 '22 22:11

ger.s.brett


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.

like image 40
Projesh Bhoumik Avatar answered Nov 07 '22 22:11

Projesh Bhoumik