如何配置POST API返回创建对象的user_id并按指定格式输出?
Got it, let's work through this to get your POST API returning exactly the format you need. You want a response that includes both a success info object and the generated user_id when creating a UserDetails instance. Here's how to implement this in your views.py using Django REST Framework:
Solution 1: Extend CreateAPIView (Recommended)
Since you're dealing with a creation operation, DRF's CreateAPIView handles most of the heavy lifting (validation, saving the object) out of the box. We just need to override its create method to return your custom response format.
from rest_framework import generics from rest_framework.response import Response from rest_framework import status from .models import UserDetails from .serializers import UserDetailsSerializer class UserDetailsCreateView(generics.CreateAPIView): queryset = UserDetails.objects.all() serializer_class = UserDetailsSerializer def create(self, request, *args, **kwargs): # Validate and save the incoming data serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # Build your required response structure custom_response = [ { "info": { "status": "SUCCESS", "message": "User Details Successfully Uploaded" }, "user_id": serializer.data['user_id'] } ] return Response(custom_response, status=status.HTTP_201_CREATED)
Breakdown of this approach:
serializer.is_valid(raise_exception=True)ensures any validation errors are automatically returned in DRF's standard error format (you can customize this too if needed, but your question focuses on the success case).self.perform_create(serializer)saves the newUserDetailsinstance to the database.- We pull the auto-generated
user_idfromserializer.data(since your serializer marksuser_idas read-only, it will be included in the serialized data after saving). - Finally, we wrap everything in the array format you specified and return it with a 201 Created status code.
Solution 2: Use APIView for Full Control
If you prefer a more explicit, hands-on approach, you can use DRF's base APIView and handle the POST logic yourself:
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import UserDetails from .serializers import UserDetailsSerializer class UserDetailsCreateView(APIView): def post(self, request): serializer = UserDetailsSerializer(data=request.data) if serializer.is_valid(): serializer.save() # Construct the custom response custom_response = [ { "info": { "status": "SUCCESS", "message": "User Details Successfully Uploaded" }, "user_id": serializer.data['user_id'] } ] return Response(custom_response, status=status.HTTP_201_CREATED) # Return validation errors if input is invalid return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Important Notes:
- Make sure your
UserDetailsmodel hasuser_idconfigured to auto-generate (e.g.,user_id = models.AutoField(primary_key=True)ormodels.BigAutoField). This ensures the value is created automatically when the object is saved, which matches your serializer'sread_only_fieldssetting. - Your existing
UserDetailsSerializeris already set up correctly withread_only_fields = ['user_id'], so clients can't send auser_idin their POST request—this is exactly what we want since the server should generate it.
内容的提问来源于stack exchange,提问作者kunwar11
相关产品推荐
相关产品推荐

