сериализатор:
class PostTopSerializator(serializers.ModelSerializer):
id_post = serializers.IntegerField(source='id')
comment_count = serializers.SerializerMethodField('get_count_comment')
rank = serializers.SerializerMethodField('get_rank')
class Meta:
model = Movie
fields = ['id_post', 'comment_count', 'rank']
def get_count_comment(self, object_id):
total_comments = Comment.objects.filter(movie_id=object_id).count()
return total_comments
def get_rank(self, object_id):
return object_id.id
Пост с наибольшим количеством комментариев получает 1-й рейтинг, 2-е место - 2-е место и так далее ...
И я получаю такой ответ:
[
{
"id_movie": 2,
"comment_count": 5,
"rank": 2
},
{
"id_movie": 1,
"comment_count": 4,
"rank": 1
},
{
"id_movie": 3,
"comment_count": 4,
"rank": 3
}
]
как реализовать логику метода:
def get_rank(self, object_id):
return object_id.id
to get the same rank with the same number of comments and the output will be:
[
{
"id_post": 2,
"comment_count": 5,
"rank": 1
},
{
"id_movie": 1,
"comment_count": 4,
"rank": 2
},
{
"id_post": 3,
"comment_count": 4,
"rank": 2
}
]