menu

Questions & Answers

Optimizing DRF performance

I am trying to optimize a DRF view that has very low performance, is there a way to make it faster? This is where I am right now

Models:

class CategoryVideos(models.Model):
    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'
    name = models.CharField(max_length=100, null=False, blank=False)

    def __str__(self):
        return f"{self.name} and {self.id}"

class Videos(models.Model):
    category = models.ManyToManyField(CategoryVideos, null=True, blank=True)
    illustration = models.FileField(null=True, blank=True) 
    video = models.FileField(null=True, blank=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    description = models.CharField(max_length=255, null=True, blank=True)
    url_video = models.CharField(max_length=255, null=True, blank=True)
    url_image = models.CharField(max_length=255, null=True, blank=True)

Serializers:

class CategorySerializer2(serializers.ModelSerializer):
    class Meta:
        model = CategoryVideos
        fields = ["name"] 

class VideoSerializer(serializers.ModelSerializer):

    category = CategorySerializer2(many=True, read_only=True) 

    class Meta:
        model = Videos
        fields = ["id", "description", "title", "url_video", "url_image", "category"]
        read_only=True

View:


class OfferListAPIView(generics.ListAPIView):
    queryset  = Videos.objects.prefetch_related('category').all()
    serializer_class=VideoSerializer

For the moment, with 400 videos and just 6 categories, it takes approx 2.8 secs to get an answer which is way too high. Many thanks

Answers(1) :

As you are using only for listing you can add db_index=True attribute for any field you can also use db_index=True to create an index on a ForeignKey and ManyToManyFields for performance.
make note that creating indexes can slow down the performance of some database operations, such as inserting or updating large amounts of data.