本文介绍了在Django Rest FrameWork中'many = True'是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习DRF,对此 many = True 代码有点困惑。它有什么作用?还是什么意思?

I am learning DRF now, im little puzzuled by this many = True code. What does it do? Or what does it mean?

示例1

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.RelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

示例2

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAdminUser,)

    def list(self, request):
        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)


推荐答案

我认为您将 many = True 与很多对千真万确的混淆,但是这些概念并非如此

I think you are confusing many=True with many to many realtionship, but the concepts is not like that

通过设置 many = Tr ue ,您告诉drf queryset包含多个项目(项目列表),因此drf需要使用序列化程序类(和 serializer.data 将是列表)

by setting many=True you tell drf that queryset contains mutiple items (a list of items) so drf needs to serialize each item with serializer class (and serializer.data will be a list)

如果未设置此参数,则表示queryset是单个实例,而 serializer.data 将是单个对象)

if you don't set this argument it means queryset is a single instance and serializer.data will be a single object)

这篇关于在Django Rest FrameWork中'many = True'是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:28