【问题标题】:Order queryset by the number of foreign key instances in a Django field按 Django 字段中外键实例的数量排序查询集
【发布时间】:2022-11-22 23:34:36
【问题描述】:

我正在尝试返回与计算博客帖子反应数量的直通表相关的对象。

我有一个文章模型、情绪模型和反应模型。情绪只是一个 1 或 2,1 代表 like2 代表 dislike。在前端,用户可以对文章做出反应,他们的反应存储在 Reactions 表中。

Reactions model

class Reaction(models.Model):
    user_id = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE)
    article_id = models.ForeignKey(Article, related_name='article_id', on_delete=models.CASCADE)
    sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE)

我想找到 2 篇最受欢迎的文章,所以我写了一个视图来处理 GET 请求

views.py

class MostPopularView(generics.RetrieveAPIView):
    queryset = Reaction.objects.annotate(num_likes = Count('sentiment_id')).order_by('num_likes')
    serializer_class = MostPopularSerializer

和一个序列化程序来转换数据

serializers.py

class MostPopularSerializer(serializers.Serializer):
    class Meta:
        fields = (
            'id',
            'title',
        )
        model = Article

按照现在的代码,我得到了回应

<QuerySet [<Reaction: d745e09b-5685-4592-ab43-766f47c73bef San Francisco Bay 1>, <Reaction: d745e09b-5685-4592-ab43-766f47c73bef The Golden Gate Bridge 1>, <Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 San Francisco Bay 1>, <Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 The Golden Gate Bridge 2>]>

显示 San Francisco Bay 有 2 个赞,The Golden Gate Bridge 有 1 个喜欢和 1 个不喜欢。

我尝试了多种方法来获得正确的响应,包括通过 sentiment=1 进行过滤,但除此之外别无他法。 我正在寻找的是一种计算 sentiment=1 字段的数量的方法,这些字段对应于每篇文章 id 并按降序排列,所以最喜欢的在顶部。

【问题讨论】:

    标签: python django count


    【解决方案1】:

    我以不同的方式解决了类似的问题。 对我来说,我想根据国家的使用频率对 Person 的查询集进行排序。

    我向模型添加了一个属性

    class Country(models.Model):
        .
        .
        def _get_count(self):
            count = len(Person.objects.filter(country=self.id))
    
            return count or 0
    
        count = property(_get_count)
    

    在视图中我有这个查询集

    qs = sorted(Country.objects.all(), key=lambda country: country.count*-1)
    

    我需要使用 python 排序,因为 django qs.order_by 不能按属性排序。 * -1 为降序

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 2020-08-16
      • 1970-01-01
      • 2010-12-11
      • 2014-01-18
      • 2011-08-10
      • 2015-08-31
      • 2012-09-30
      • 1970-01-01
      相关资源
      最近更新 更多