#django #django-rest-framework
Вопрос:
У меня есть два таких серилизатора :
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)
в views.py мне нужно получить данные из модели свободного времени и снова отправить их в SetTimeZoneSerializer(мне нужно сериализовать результаты фильтра запросов, и это вложенное поле). :
@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)
и я получил эту ошибку :
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
Ответ №1:
если у вас есть сериализатор для этой модели, почему бы просто не использовать его
замените эту строку
j['time_table'] = FreeTime.objects.all().values()
с
j['time_table'] = UsersInfoSeriliazerByUsers(FreeTime.objects.all().values(), many=True).data