【问题标题】:Django : Get the highest queryset attribute in my templateDjango:在我的模板中获取最高的查询集属性
【发布时间】:2019-03-09 12:42:44
【问题描述】:

我从 Django 开始,我想知道如何从我的 Django 查询集中获取属性。

我有这个查询集:

get_country = Download.objects.filter(pub__publication__id=pubsd.id).values('country__name').order_by('country__name').annotate(count_country=Count('country__name'))

返回:

<QuerySet [{'country__name': 'France', 'count_country': 1}, {'country__name': 'Germany', 'count_country': 2}]>

所以我想在我的模板中显示count_country最高的国家/地区名称

我想知道我该怎么做?

非常感谢

【问题讨论】:

  • 所以你只对Country和Downloads最多的Country感兴趣?
  • 是的,从下载次数最多的国家/地区获取名称;)

标签: django django-queryset


【解决方案1】:

我认为你最好反过来查询,比如:

max_country = Country.objects.filter(
    download__pub__publication__id=pubsd.id
).annotate(
    ndown=Count('download')
).order_by('-ndown').first()

(这里有download related_name 与Country 到Download 的关系)。

这将为您提供具有最相关Downloads 的Country 对象,然后您可以对Country 对象进行处理或渲染,就像您可以对任何Country 对象执行的操作一样。

例如,如果您将对象传递给模板,则可以将其渲染为:

Most downloads are from {{ max_country.name }}

【讨论】:

  • 我尝试了您的查询集,并在下载模型中添加了related_name,但它没有显示出好的结果。对于给定的出版物,我有 2 个德国和 1 个法国,它给了我“法国”。所以不是最高的国家。哼,我得看看为什么;)
  • 好吧,我明白为什么了,这是因为在我的查询集中我对特定的出版物设置了过滤器。我必须用我的过滤器处理你的查询集。但我希望它不会那么难。所以你的查询集暂时不起作用。而且我不能像以前那样在你的过滤器中添加过滤器,因为你是通过国家请求而不是下载?
  • @user10390326: 嗯.. 添加过滤器有帮助吗?
  • 是的,完美!我在download__pub__publication__id=pubsd.id 中忘记了download,这就是它不起作用的原因:)
【解决方案2】:

在视图中

return render(request,'template.html','{'country':'get_country'}

在模板中

{% for key, values in country.items %}
    <tr>
        <td>{{key}}</td>
        <td>{{values }}</td>
    </tr>
    {% endfor %}


get_country = Download.objects.filter(pub__publication__id=pubsd.id).values('country__name').order_by('country__name').annotate(count_country=Count('country__name')).order_by('-count_country')

【讨论】:

  • 如果不运行您的代码,我认为它不会返回最先进的国家
  • 这取决于您生成的查询集。为此我给出了代码,否则在我的答案中尝试查询集
  • 我在您的回答中尝试了查询集,但没有得到预期的结果。不过谢谢你的评论!
猜你喜欢
  • 2021-09-20
  • 2016-04-17
  • 2020-09-12
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 2018-06-06
  • 2021-06-06
  • 2023-03-14
相关资源
最近更新 更多