Django REST Framework - Limit for Nested Serializer

Viewed 1003

I have the following models.py:

class Category(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100, blank=False)

class Movie(models.Model):

    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100, blank=False)
    category = models.ForeignKey(Category,related_name='movies',
                               on_delete=models.CASCADE,
                               blank=True,
                               null=True)

As you can see, there is a ForeignKey relationship between the two classes. A Category can have multiple movies, but a Movie belongs to only one Category. My serializers.py looks like the following:

class CategorySerializer(serializers.HyperlinkedModelSerializer):

    movies = MoviesSerializer(many=True, read_only=True)
    class Meta:
        model = Category
        fields = ('url','id','created','name', 'movies')

class MovieSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Movie
        fields = ('url','id','created','name', 'category')

So, I have nested serializers. When I deserialize the content of the categories, then it shows me also the nested movies in the JSON output as I expected. But it shows me ALL movies belonging to a particular category in the JSON output. How can I limit this number ?

I tried this solution but it did not worked for me because I use serializers.HyperlinkedModelSerializer. In that provided solution they used serializers.ModelSerializer. I got this error when I tried that solution:

AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.

UPDATE: Here is my views.py:

class AllCategories(generics.ListAPIView):
    '''
        This class class-based view lists
        all the categories created 
    '''
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

    def list(self, request, *args, **kwargs):
        '''
            standard method that we override just to
            put the string 'allCategories' before the dataset
        '''
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        # the only part we change
        return Response({'allCategories': serializer.data})


class AllMovies(generics.ListAPIView):
    '''
        This class lists all the movies
    '''
    # define the serializer class 
    serializer_class = MovieSerializer
    queryset = Movie.objects.all()

    def list(self, request, *args, **kwargs):
        '''
            standard method that we override just to
            put the string 'allMoviesOfUser' before the dataset
        '''
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        # the only part we change
        return Response({'allMoviesOfUser': serializer.data}) 
0 Answers
Related