@@ -183,6 +183,50 @@ def test_patch(self, client):
183183 }
184184 }
185185
186+ @pytest .mark .urls (__name__ )
187+ def test_post_with_missing_id (self , client ):
188+ data = {
189+ "data" : {
190+ "id" : None ,
191+ "type" : "custom" ,
192+ "attributes" : {"body" : "hello" },
193+ }
194+ }
195+
196+ url = reverse ("custom" )
197+
198+ response = client .post (url , data = data )
199+ assert response .status_code == status .HTTP_200_OK
200+ assert response .json () == {
201+ "data" : {
202+ "type" : "custom" ,
203+ "id" : None ,
204+ "attributes" : {"body" : "hello" },
205+ }
206+ }
207+
208+ @pytest .mark .urls (__name__ )
209+ def test_patch_with_custom_id (self , client ):
210+ data = {
211+ "data" : {
212+ "id" : 2_193_102 ,
213+ "type" : "custom" ,
214+ "attributes" : {"body" : "hello" },
215+ }
216+ }
217+
218+ url = reverse ("custom-id" )
219+
220+ response = client .patch (url , data = data )
221+ assert response .status_code == status .HTTP_200_OK
222+ assert response .json () == {
223+ "data" : {
224+ "type" : "custom" ,
225+ "id" : "2176ce" , # get_id() -> hex
226+ "attributes" : {"body" : "hello" },
227+ }
228+ }
229+
186230
187231# Routing setup
188232
@@ -202,6 +246,14 @@ class CustomModelSerializer(serializers.Serializer):
202246 id = serializers .IntegerField ()
203247
204248
249+ class CustomIdModelSerializer (serializers .Serializer ):
250+ id = serializers .SerializerMethodField ()
251+ body = serializers .CharField ()
252+
253+ def get_id (self , obj ):
254+ return hex (obj .id )[2 :]
255+
256+
205257class CustomAPIView (APIView ):
206258 parser_classes = [JSONParser ]
207259 renderer_classes = [JSONRenderer ]
@@ -211,11 +263,26 @@ def patch(self, request, *args, **kwargs):
211263 serializer = CustomModelSerializer (CustomModel (request .data ))
212264 return Response (status = status .HTTP_200_OK , data = serializer .data )
213265
266+ def post (self , request , * args , ** kwargs ):
267+ serializer = CustomModelSerializer (request .data )
268+ return Response (status = status .HTTP_200_OK , data = serializer .data )
269+
270+
271+ class CustomIdAPIView (APIView ):
272+ parser_classes = [JSONParser ]
273+ renderer_classes = [JSONRenderer ]
274+ resource_name = "custom"
275+
276+ def patch (self , request , * args , ** kwargs ):
277+ serializer = CustomIdModelSerializer (CustomModel (request .data ))
278+ return Response (status = status .HTTP_200_OK , data = serializer .data )
279+
214280
215281router = SimpleRouter ()
216282router .register (r"basic_models" , BasicModelViewSet , basename = "basic-model" )
217283
218284urlpatterns = [
219285 path ("custom" , CustomAPIView .as_view (), name = "custom" ),
286+ path ("custom-id" , CustomIdAPIView .as_view (), name = "custom-id" ),
220287]
221288urlpatterns += router .urls
0 commit comments