2015-02-26 15 views
7

Sto cercando di fare una matrice JSON in Django, ma sto ottenendo errore -Creazione matrice JSON in Django

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

e la mia views.py -

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

Fondamentalmente user_post è un modello un i post sono l'oggetto dei primi 20 dati salvati. Voglio inviare un array JSON ma non riesco a convertire i post in un array JSON. Ho anche provato i serializzatori ma non mi ha aiutato.

Sono bloccato aiutatemi per favore.

Grazie in anticipo.

risposta

20

Questo risolverebbe il tuo problema?

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) 
+0

Grazie ha funzionato, ma ora non riesco a ottenere i dati. Puoi dirmi come posso recuperare i dati JSON ... ?? – aquaman

+0

Mi dispiace che ci sia stato un errore nel post = ... linea. Mancava la chiamata alla funzione all(). Funziona per te adesso? –

1

Penso che si possa risolvere questo problema utilizzando sicuro = false

ritorno JsonResponse (messaggi, cassaforte = False)

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

     return JsonResponse(posts, safe=False)