Python Django查询多个

Python Django查询多个,python,django,django-rest-framework,Python,Django,Django Rest Framework,我想做一个查询,以选择前5名用户与更多喜欢在他们的职位 我的模型是: class Post(ModelBase): title=models.CharField('title',最大长度=255) description=models.TextField() finished=models.BooleanField(默认值=False) author=models.ForeignKey(用户,在\u delete=models.CASCADE上,相关的\u name='post\u author

我想做一个查询,以选择前5名用户与更多喜欢在他们的职位

我的模型是:

class Post(ModelBase):
title=models.CharField('title',最大长度=255)
description=models.TextField()
finished=models.BooleanField(默认值=False)
author=models.ForeignKey(用户,在\u delete=models.CASCADE上,相关的\u name='post\u author')
likes=models.ManyToManyField(用户,通过class='PostLike',)
tags=models.ManyToManyField(Tag,related_name='tags')
def total_likes(自我):
return self.likes.count()
类PostLike(ModelBase):
post=models.ForeignKey(post,on_delete=models.CASCADE)
user=models.ForeignKey(用户,on_delete=models.CASCADE)
我有这个,但它不适合我。不要告诉用户喜欢的帖子,而是计算每个用户给出的喜欢度

users = User.objects.annotate(likes_count=Count('postlike', Q(post__is_active=True)))\
        .order_by('likes_count').reverse()[0:5]

您不需要注释
postlike
Count
,而需要注释
post\u author\u\u likes
的计数(通过设置的相关名称遍历关系):

users = User.objects.annotate(
    likes_count=Count(
        'post_author__likes',
        filter=Q(post_author__is_active=True)
    )
).order_by('-likes_count')[0:5]