Home > Back-end >  Something wrong with django json serializer
Something wrong with django json serializer

Time:09-24

i try looking for answers but so far to no avail, basically i try to return django model as json however, it seem that the serializer convert it to string instead

my code is as follow:

view.py

from django.shortcuts import render
from screener.models import maintable
from .models import Messages
from django.http import JsonResponse
from django.core import serializers
from datetime import datetime
import json

def infiniteScroll(request, room_name):
    dateFilter=request.GET.get('date')
    dateFilter=dateFilter[5:len(dateFilter)-4]
    dateFilter=datetime.strptime(dateFilter, '%d %b %Y %H:%M:%S')
    data=serializers.serialize('json', reversed(Messages.objects.filter(room=room_name).filter(date_added__lt=dateFilter).order_by('-date_added')[:2]))
    return JsonResponse(data, safe=False)

urls.py

from django.contrib import admin
from django.urls import path
from . import views

app_name='chat'
urlpatterns = [
    path('<str:room_name>/', views.room, name='room'),
    path('<str:room_name>/hist/', views.infiniteScroll, name='infiniteScroll'),
]

when i go to the site http://127.0.0.1:8000/chat/AAPL/hist/?date=Thu, 23 Sep 2021 14:03:42 GMT

the result is a page with string instead:

"[{\"model\": \"chat.messages\", \"pk\": 118, \"fields\": {\"username\": \"adiputra12\", \"room\": \"AAPL\", \"content\": \"hello\", \"date_added\": \"2021-09-23T13:54:30.043Z\"}}]"

how can I return json instead like shown below:

[{'model': 'chat.messages', 'pk': 118, 'fields': {'username': 'adiputra12', 'room': 'AAPL', 'content': 'hello', 'date_added': '2021-09-23T13:54:30.043Z'}]

CodePudding user response:

After This line of code

data=serializers.serialize('json',reversed(Messages.objects.filter(room=room_name).filter(date_added__lt=dateFilter).order_by('-date_added')[:2]))

Try adding

data = json.loads(data)
return JsonResponse(data, safe=False)
  • Related