22

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

example 1

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

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

example 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)
4
  • 2
    Did you read the documentation for serializers? Commented Jul 7, 2018 at 13:04
  • 1
    Check this question also stackoverflow.com/questions/49976679/… Commented Jul 7, 2018 at 13:07
  • @DanielRoseman yeah sir , have read it that's why i am getting confused in serializer relationship its written many - If applied to a to-many relationship, you should set this argument to True. then in serializers its written To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True ... one code but two different explanations is making me confused.. Commented Jul 7, 2018 at 13:19
  • What's different about those explanations? The both say that if you have multiple objects, set it to true. Commented Jul 7, 2018 at 14:52

1 Answer 1

53

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

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)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.