You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置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:

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 new UserDetails instance to the database.
  • We pull the auto-generated user_id from serializer.data (since your serializer marks user_id as 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 UserDetails model has user_id configured to auto-generate (e.g., user_id = models.AutoField(primary_key=True) or models.BigAutoField). This ensures the value is created automatically when the object is saved, which matches your serializer's read_only_fields setting.
  • Your existing UserDetailsSerializer is already set up correctly with read_only_fields = ['user_id'], so clients can't send a user_id in their POST request—this is exactly what we want since the server should generate it.

内容的提问来源于stack exchange,提问作者kunwar11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:02:45