Aran Freel
Aran Freel

Reputation: 3215

Django Rest Framework what is the meaning of arguments being passed to the ModelSerializer?

I am trying to understand the arguments which are being passed into the serializers.ListUserSerializer(). I understand that last_five is the data to be returned through the serializer.

Where I fail to understand is where this model has a to-many relationship. From reading the DRF documentation, many=True is passed when the model has a to-many relationship. However, I do not understand how this is specifying the to-many relationship. I see a couple of possibilities . . .

Also I am not quite understanding the context argument. I think that it is simply the request call to the api being included in the payload to the client.

The code base for this is here

    class ExploreUsers(APIView):

        def get(self, request, format=None):

            # the "-date_joined" specifies descending order vs "date_joined"
            last_five = models.User.objects.all().order_by('-date_joined')[:5]

            # many=True provides to-many relationship from one user to many users
            serializer = serializers.ListUserSerializer(
                last_five, many=True, context={"request": request})

            return Response(data=serializer.data, status=status.HTTP_200_OK)

Upvotes: 0

Views: 43

Answers (1)

JPG
JPG

Reputation: 88509

many = True
By setting many=True you tell DRF that the object you are passing contains multiple items (a list of items) so DRF needs to serialize each item with serializer class (and serializer.data will be a list)

Here you are passing queryset which is a list like object (list of object of model class)

context
context is a (or should be) dict, which is passed to your serializer and you could access the context data anywhere in your serializer by self.context['key']

EXAMPLE

# serializer.py
class MySerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.SerializerMethodField(required=False)

    def get_age(self, age):
        if self.context['age']:
            return self.context['age']
        return None


# usage
sample_data = {"name": "your name"}
serializer = MySerializer(data=sample_data, context={'age': 12})
serializer.is_valid(True)
print(serializer.data)

Upvotes: 1

Related Questions