2

I have this dictionary which I need to pass to another view, knowing that possible ways of doing that are either through sessions or cache, now when I am trying to pass to session it is throwing me an error that data is not JSON serializable probably because I have DateTime fields inside this dictionary

  session_data = serializers.serialize('json',session_data)

error on above statement

'str' object has no attribute '_meta'

updated date is somewhat in this format

{'city_name': 'Srinagar', 'description': 'few clouds', 'temp': 26.74, 'feels_like': 27.07, 'max_temp': 26.74, 'min_temp': 26.74, 'sunrise': datetime.time(6, 11, 10), 'sunset': datetime.time(18, 43, 59)}
4
  • You session_data seems to be a string already, not a model object. Commented Sep 11, 2021 at 7:37
  • not entirely it has some DateTime fields, it is a dictionary as I am passing it as a context to template as well Commented Sep 11, 2021 at 7:39
  • 1
    "dictionary" well there is your problem, serializers.serialize is supposed to be passed either a queryset or an iterable of model instances. Commented Sep 11, 2021 at 7:40
  • is there any way out of using any kind of serializer, or do i have to manually make changes because there is a lot of data and the process is tedious Commented Sep 11, 2021 at 7:42

1 Answer 1

3

Your session_data is already a dictionary. Since Django's serializer focuses on serializing an iterable of model object, that thus will not work.

You can make use of Django's DjangoJSONEncoder [Django-doc] to serialize Python objects that include date, datetime, time and/or timedelta objects.

You thus can work with:

from django.core.serializers.json import DjangoJSONEncoder

encoder = DjangoJSONEncoder()
session_data = encoder.encode(session_data)

If you plan to return a JSON blob as a HTTP response, you can simply let the JsonResponse do the encoding work:

from django.http import JsonResponse

# …
return JsonResponse(session_data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.