[Django]-Creating json array in django

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) 

7👍

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.

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.

Leave a comment