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

如何在Django REST Framework中调整Serializer,使employer_info嵌套在结果项内

Fixing Employer Info Placement in Django REST Framework Response

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 @staticmethod decorator
  • Added self as the first parameter to get_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 SerializerMethodField will now generate the employer_info field 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 results array.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:52:29