Django drf序列化程序无法在to_representation中获取多个实例

问题描述 投票:0回答:1

我的视图类看起来像,

views.py

class UserHierarchyOfOrganizations(viewsets.GenericViewSet, mixins.ListModelMixin):

    serializer_class = UserListOrganizationHierarchySerializer

    def get_queryset(self):
        user_ids = map(int, self.request.query_params['users'].split(','))
        return User.objects.filter(id__in=list(user_ids)).select_related('organization')

serializers.py

class UserOrganizationHierarchySerializer(serializers.ModelSerializer):
    # user_ids = serializers.ListField(
    #             child=serializers.IntegerField(min_value=1, validators=[]
    #             ), required=True
    #            )
    # user_id = serializers.IntegerField(min_value=1, read_only=True)
    # organizations = OrganizationReadOnlySerializer(read_only=True)

    class Meta:
        model = User
        fields = ('pk',)
        # read_only_fields = ('organizations','user_id')

    def to_representation(self, instance):
        out = super().to_representation(instance)
        print(out)
        out = OrganizationReadOnlySerializer(instance.organization).data
        print (out)
        return out

class UserListOrganizationHierarchySerializer(serializers.ModelSerializer):
    # organization_hierarchy = serializers.ReadOnlyField()
    #organization_hierarchy = serializers.ListField(child=UserOrganizationHierarchySerializer(read_only=True))
    organization_hierarchy = serializers.SerializerMethodField('_get_org_hierarchy')

    def _get_org_hierarchy(self, obj):
         print (type(obj))
         serializer = UserOrganizationHierarchySerializer(obj, many=True)
         return serializer.data

    class Meta:
        model = User
        fields = ('organization_hierarchy',)
        read_only_fields = ('organization_hierarchy',)

    def to_representation(self, instance):
        out = super().to_representation(instance)
        return out

但我在_get_org_hierarchyto_representation方法中获得单个用户实例而不是多个用户实例。

有没有办法在UserListOrganizationHierarchySerializer序列化器中获取User类的多个实例(请参阅get_queryset方法)?

我想要实现的是,

{
  "organization_hierarchy": [ 
     {"id": 1, "organizations": "foo -> bar"},
  ]
}
python django django-rest-framework
1个回答
1
投票

据我所知,你需要在你的视图中访问你的get_queryset(),对吧?然后尝试用这个替换你的_get_org_hierarchy(self, obj)

def _get_org_hierarchy(self, obj):
    queryset = self.context['view'].get_queryset()  # to get results of get_queryset() from your view
    serializer = UserOrganizationHierarchySerializer(queryset, many=True)
    return serializer.data

© www.soinside.com 2019 - 2024. All rights reserved.