[Django]-Django rest framework – filtering for serializer field

103👍

How about something like this:

class ProductSerializer(serializers.ModelSerializer):
    likes = serializers.SerializerMethodField()

    def get_likes(self, product):
        qs = Like.objects.filter(whether_like=True, product=product)
        serializer = LikeSerializer(instance=qs, many=True)
        return serializer.data

    class Meta:
        model = Product
        fields = ('id', 'name', 'likes')

**LikeSerializer omitted for brevity.

42👍

Instead of SerializerMethodField, which causes one additional database query per object, you can now (starting with Django 1.7) use Prefetch objects in the queryset of your DRF ViewSet:

from rest_framework import viewsets
from django.db.models import Prefetch

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.prefetch_related(Prefetch(
        'likes',
        queryset=Like.objects.filter(like=True)))

The prefetch needs just one query, ensuring vastly superior performance compared to SerializerMethodField.

Leave a comment