如何在Django REST Framework中调整Serializer,使employer_info嵌套在结果项内
The issue you're facing comes from two key points: an incorrect method signature in your serializer and likely manual addition of employer_info at the top level of your paginated response. Here's how to fix it step by step:
1. Correct the SerializerMethodField Getter
Your get_employer_info method is marked as a staticmethod, which doesn't align with Django REST Framework's expectations for SerializerMethodField handlers. DRF expects these methods to be instance methods (taking self as the first parameter) to properly interact with the serializer context.
Update your serializer like this:
class EmployeeListSerializer(serializers.ModelSerializer): """ Employee List view get """ user_profile = UserProfileSerializer() employer_info = serializers.SerializerMethodField() def get_employer_info(self, instance): """ To get employer info :return: """ return UserEmployeeCreatedBySerializer(instance.employer_info()).data class Meta(object): """ User meta class. """ model = User fields = ('id', 'first_name', 'last_name', 'full_name', 'email', 'phone', 'user_profile', 'employer_info')
- Removed the
@staticmethoddecorator - Added
selfas the first parameter toget_employer_info
2. Remove Top-Level Employer Info from Your View
Your current response shows employer_info at the same level as count and results, which means your view is likely manually adding this field to the paginated response data. Locate and remove this code from your view.
For example, if your view has something like this:
class EmployeeListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = EmployeeListSerializer pagination_class = PageNumberPagination def get_paginated_response(self, data): response = super().get_paginated_response(data) # Remove this line that adds employer_info to the top level # response.data['employer_info'] = UserEmployeeCreatedBySerializer(...).data return response
Delete the line where you're manually inserting employer_info into the response data.
Why This Works
- The corrected
SerializerMethodFieldwill now generate theemployer_infofield for each individual User instance in your queryset, embedding it directly in each result object. - Removing the manual top-level addition ensures the field only appears where you want it: nested inside each user entry in the
resultsarray.
After making these changes, your API response will match the desired format, with employer_info present in every item of the results array and no longer at the top level of the data object.
内容的提问来源于stack exchange,提问作者Robin Chauhan

