django REST framework - limited queryset for nested ModelSerializer?

In your View Set you may specify the queryset like follows:

from rest_framework import serializers, viewsets

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()[:500]
    serializer_class = MyModelSerializer

I think what you are looking for is the SerializerMethodField.

So your code would look as follows:

class ContainerSerializer(serializers.ModelSerializer):
    items = SerializerMethodField('get_items')

    class Meta:
        model = Container
        fields = ('size', 'shape', 'items')

    def get_items(self, container):
        items = Item.objects.filter(container=container)[:500]  # Whatever your query may be
        serializer = ItemSerializer(instance=items, many=True)
        return serializer.data

The one catch is that the SerializerMethodField is read only.


You may use source parameter

class Container(models.Model):
    ...
    def get_items(self):
        return self.items[:500]

and in serializer

items = ItemSerializer(many=True, source='get_items', )