Я получаю ошибку этого типа при попытке вернуть JsonResponse. В коде python_serializer
находится объект, у которого есть переменная экземпляра с именем data, содержащая результаты JsonParser().parse(request)
словаря типа (в python). Позже в коде, когда я пытаюсь вернуть ответ json, моя программа продолжает выдавать мне эту ошибку: TypeError: int() argument must be a string, a bytes-like object or a number, not 'ObjectId'
Вот полная трассировка:
Internal Server Error: /api/products
Traceback (most recent call last):
File "C:\Users\alexei\Columns\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\alexei\Columns\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\alexei\Columns\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\alexei\Columns\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\alexei\Columns\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs)
File "C:\Users\alexei\MongoDBClone\DjangoRestApi\Product\views.py", line 29, in product_list
return JsonResponse(product_serializer.data, status=status.HTTP_201_CREATED)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\serializers.py", line 562, in data
ret = super().data
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\fields.py", line 994, in to_representation
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'ObjectId'
Модель продукта:
class Product(models.Model):
partNumber = models.CharField(max_length=70, blank=False, default='defaultPartNum')
description = models.TextField(blank=False, default='Default Description')
''
Сериализатор:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
''
Просмотр:
@api_view(['GET', 'POST', 'DELETE'])
def product_list(request):
if request.method == 'GET':
products = Product.objects.all()
searchedPartnum = request.GET.get('partNumber', None)
if searchedPartnum is not None:
products = products.filter(searchedPartnum__icontains=searchedPartnum)
productSearializer = ProductSerializer(products, many=True)
return JsonResponse(productSearializer.data, safe=False)
elif request.method == 'POST':
product_data = JSONParser().parse(request)
product_serializer = ProductSerializer(data=product_data)
if product_serializer.is_valid():
product_serializer.save()
return JsonResponse(product_serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(product_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.METHOD == 'DELETE':
count = Product.objects.all().delete()
return JsonResponse({'message': '{} Products were deleted'.format(count[0])}, status=status.HTTP_204_NO_CONTENT)