简体   繁体   中英

DRF Add multiple annotated fields to nested serializer

In my queryset i have few annotate fields. I want group those fields to nested serializer. For example

views.py

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all().prefetch_related(
        Prefetch('comments', queryset=Comment.objects.filter(parent__isnull=True).order_by('-pub_date')
                 .annotate(likes=Count('votes', filter=Q(votes__choice=True)), 
                           dislikes=Count('votes', filter=Q(votes__choice=False)))))

So there is two additional fields 'likes', 'dislikes'

serializers.py

class CommentVoteSerializer(serializers.Serializer):
    likes = serializers.IntegerField(source='comments.likes')
    dislikes = serializers.IntegerField(source='comments.dislikes')

    class Meta:
        fields = ['likes', 'dislikes']


class CommentSerializer(serializers.ModelSerializer):
    rating = CommentLikesSerializer(read_only=True, many=True)

    class Meta:
        model = Comment
        fields = ['id', 'text', 'pub_date', 'rating']

I tried different ways but can't understand how to fix it. Thanks for help

In class Meta: You forgot the model. if you give "rating" as variable name to the serializer you want to add in the fields of the other serializer then you also need to go to models.py and I guess you have a ManyToMany field there for the votes, then you must add the following argument related_name="rating".

Does your model Votes has only a boolean field for like and dislike? If yes, then I recommend to delete the entire table and the ManyToMany field and have a field an IntegerField instead of total votes in "Comment". Then increment or decrement that each time after a user request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM