My Django REST Framework API is working just as expected. In view.py, I modify OrderViewSet, def partial_update, to add another key/value pair to the response.data dict before it is saved to the db. It works without errors when I call the API with Postman.
However, when I run tests for the same functionality it fails and returns:
request.data["submission_date"] = datetime.now()
AttributeError: This QueryDict instance is immutable
Why would I get this error during testing if it is not occurring during actual API use?
View.py
class OrderViewSet(viewsets.ModelViewSet):
""" Includes custom PATCH functionality """
queryset = Order.objects.all().order_by('-order_date')
serializer_class = OrderSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = [permissions.IsAuthenticated]
def partial_update(self, request, *args, **kwargs):
""" Update status and timestamp fields accordingly """
status = request.data['status']
if status == 'submitted':
request.data["submission_date"] = datetime.now()
if status == 'packaged':
request.data["packaged_date"] = datetime.now()
if status in ['sold', 'canceled', 'abandoned']:
request.data["finished_date"] = datetime.now()
return super().partial_update(request, *args, **kwargs)
Test.py
def test_patch_order_status_from_cart_to_submitted(self):
""" test patching order status from cart to submitted """
order = sample_order(user=self.user)
payload = {
"status": "submitted"
}
res = self.client.patch(order_detail_url(order.id), payload)
self.assertEqual(res.status_code, status.HTTP_200_OK)
patched_order = Order.objects.get(id=order.id)
self.assertEqual(patched_order.status, 'submitted')
def test_submitted_timestamp(self):
""" test that patching order status to submitted also leaves timestamp """
order = sample_order(user=self.user)
payload = {
"status": "submitted"
}
self.client.patch(order_detail_url(order.id), payload)
patched_order = Order.objects.get(id=order.id)
self.assertNotEqual(patched_order.submission_date, None)
Edit:
If I were to modify a copy of request.data as below, how could I then return it from the function?
def partial_update(self, request, *args, **kwargs):
""" Update status and timestamp accordingly """
modified_data = request.data.copy()
status = request.data['status']
if status == 'submitted':
modified_data["submission_date"] = datetime.now()
if status == 'packaged':
modified_data["packaged_date"] = datetime.now()
if status in ['sold', 'canceled', 'abandoned']:
modified_data["finished_date"] = datetime.now()
return super().partial_update(request, *args, **kwargs)
Solution: Now the tests pass.
views.py:
...
def partial_update(self, request, pk, *args, **kwargs):
""" Update status and timestamp accordingly """
order = Order.objects.get(id=pk)
serializer = OrderSerializer(order, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
Serializers.py:
class OrderSerializer(serializers.ModelSerializer):
def update(self, order, validated_data):
""" Update status and timestamp accordingly """
status = validated_data.get('status')
order.status = status
if status == 'submitted':
order.submission_date = datetime.now()
elif status == 'packaged':
order.packaged_date = datetime.now()
elif status in ['sold', 'canceled', 'abandoned']:
order.finished_date = datetime.now()
order.save()
return order
class Meta:
model = Order
fields = '__all__'
read_only_fields = ('id', 'user')