Home > Software design >  nested serializer filed TypeError: Object of type QuerySet is not JSON serializable
nested serializer filed TypeError: Object of type QuerySet is not JSON serializable

Time:09-30

I have two serilizers like this :

class UsersInfoSeriliazerByUsers(serializers.ModelSerializer):
class Meta:
    model = FreeTime
    fields = '__all__'


class SetTimeZoneSerializer(serializers.Serializer):
  TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
    meeting_date = serializers.DateField(format="%d-%m-%Y", input_formats=   ['%d-%m-%Y', 'iso-8601'])
time_zone_destination = serializers.ChoiceField(
                    choices = TIMEZONES)

    time_table = UsersInfoSeriliazerByUsers(many=True,read_only=True)

in views.py i need to get data from freetime model and send it to SetTimeZoneSerializer again(i need to serialize the queryfilter results and it is a nested field ) :

  @action(detail=False, methods=['post'])
def common(self,request):
    serializer = SetTimeZoneSerializer(data = request.data)
    if serializer.is_valid():
        j={}
   
        j['meeting_date']=serializer.data['meeting_date']
        j['time_zone_destination']=serializer.data['time_zone_destination']
        j['time_table'] =  FreeTime.objects.all().values()
        json_string = json.dumps(j)
        serializer = SetTimeZoneSerializer(json_string, many=True)

and i got this error :

    Internal Server Error: /api/time/common/
Traceback (most recent call last):
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/admin1/mizbanproject/time-algorithm/time_algorithm_api/api/views.py", line 114, in common
    json_string = json.dumps(j)
  File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type QuerySet is not JSON serializable

CodePudding user response:

when you have a Serializer for that Model why not simply use it

replace this line

j['time_table'] =  FreeTime.objects.all().values()

with

j['time_table'] =  UsersInfoSeriliazerByUsers(FreeTime.objects.all().values(), many=True).data
  • Related