按帖子评论等级排序的用户列表

时间:2019-08-13 11:22:28

标签: python django django-models django-rest-framework

我想制作一个API End Point,以便该用户可以按照其帖子评论获得其所在城市的用户列表

我在帖子模型中定义了一种方法来计算总评论(赞成和反对),我在想可以通过以下途径实现解决方案,但我不确定{{1} }和groupBy post_owner中,但是我不知道如何在Django中完成

发布模型

orderBy sum(count_reactions())

我的用户模型

class Post(models.Model):
    title = models.TextField(max_length=255, default='Title')
    post_owner = models.ForeignKey(MyUser, on_delete=models.CASCADE)
    description = models.TextField(max_length=255)
    city = models.ForeignKey(City, related_name='location', on_delete=models.CASCADE)
    longitude = models.CharField(max_length=255)
    image = models.CharField(max_length=255,
                             default='https://www.eltis.org/sites/default/files/styles/web_quality/public/default_images/photo_default_2.png')
    latitude = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

    def count_reactions(self):
        likes_count = Reaction.objects.filter(post=self.id, is_like=True).count()
        dislikes_count = Reaction.objects.filter(post=self.id, is_like=False).count()
        return likes_count - dislikes_count

    def owner(self):
        return self.post_owner

反应模型

class MyUser(AbstractUser):
    phone_number = models.BigIntegerField(blank=False, unique=True)
    city = models.ForeignKey(City, related_name='city', on_delete=models.CASCADE)
    address = models.CharField(max_length=255)

    def owner(self):
        return self

预期结果是按帖子评论获得用户的有序列表,但只有同一城市(class Reaction(models.Model): reaction_owner = models.ForeignKey(MyUser, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='reactions', on_delete=models.CASCADE) is_like = models.BooleanField(null=False) def owner(self): return self.reaction_owner 模型中的城市字段)的用户

2 个答案:

答案 0 :(得分:1)

您可以将所有内容合并为一个查询。

根据Reaction命名查询的位置,看起来应该像这样:

# Filter for the city you want
users = MyUser.objects.filter(city=your_city_obj)

# Then doing the calculations
users = users.annotate(rank_point=(Count('post__reactions', filter=Q(post__reactions__is_like=True)) - (Count('post__reactions', filter=Q(post__reactions__is_like=False)))))

# And finaly, order the results
users = users.order_by('-rank_point')

答案 1 :(得分:1)

答案是Navid's,但通过排除排名等于零的用户并包括限制来完成答案

# Filter for the city you want
users = MyUser.objects.filter(city=your_city_obj)

# Then doing the calculations
users = users.annotate(rank_point=(Count('post__reactions', filter=Q(post__reactions__is_like=True)) - (Count('post__reactions', filter=Q(post__reactions__is_like=False))))).filter(rank_point__gt=0)

# And finaly, order the results
users = users.order_by('-rank_point')[:LIMIT]