20

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)
Chidananda Nayak
  • 1,161
  • 1
  • 13
  • 45
  • 1
    Did you read the [documentation for serializers](http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects)? – Daniel Roseman Jul 07 '18 at 13:04
  • 1
    Check this question also https://stackoverflow.com/questions/49976679/need-help-understanding-many-and-source-fields-in-a-serializer/ – neverwalkaloner Jul 07 '18 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.. – Chidananda Nayak Jul 07 '18 at 13:19
  • What's different about those explanations? The both say that if you have multiple objects, set it to true. – Daniel Roseman Jul 07 '18 at 14:52

1 Answers1

51

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)

aliva
  • 5,450
  • 1
  • 33
  • 44