Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'many = True' do in Django Rest FrameWork?

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)
like image 957
Chidananda Nayak Avatar asked Jul 07 '18 12:07

Chidananda Nayak


People also ask

What is Read_only true in Django?

Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.

Why do we use Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is difference between Api_view and ViewSet?

APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.


1 Answers

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)

like image 187
aliva Avatar answered Sep 18 '22 00:09

aliva