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
.
- [Django]-How to annotate Count with a condition in a Django queryset
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-How to set up a PostgreSQL database in Django
Source:stackexchange.com