我找不到这个问题的答案。所以这是我的问题。对于一个新项目,我想使用 django-taggit .
有人对如何基于当前查询集创建标签云有建议吗?
理想的行为是从一个未过滤的列表“开始”——然后通过应用过滤器和标签来缩小结果范围。在开头,标签云显示例如50 个最常见的标签。选择标签(或其他标准)后,标签云应该只显示剩余的可能性。
我知道django-tagging为这种情况提供 Tag.objects.usage_for_queryset()。但我更愿意使用“-taggit”而不是“-tagging”。
最佳答案
django-taggit-templatetags似乎是 django-taggit 的 tagcloud 的“首选”位置。
虽然它似乎不处理查询集。 :(
所以,我添加了:
@register.inclusion_tag('taggit_templatetags/tagcloud_include_qs.html')
def include_tagcloud_qs(queryset):
try:
queryset = queryset.annotate(num_times=Count('taggeditem_items'))
except FieldError:
queryset = queryset.annotate(num_times=Count('taggit_taggeditem_items'))
num_times = queryset.values_list('num_times', flat=True)
weight_fun = get_weight_fun(T_MIN, T_MAX, min(num_times), max(num_times))
queryset = queryset.order_by('name')
for tag in queryset:
tag.weight = weight_fun(tag.num_times)
return {"tags": queryset}
到
templatetags/taggit_extras.py
并将此添加到位于 taggit_templatetags/tagcloud_include_qs.html 的新文件
<div>
{% for tag in tags %}
<font size={{tag.weight|floatformat:0}}>{{tag}}</font>
{% endfor %}
</div>
我在我的模板中像这样使用它:
{% include_tagcloud_qs my_queryset %}
我没有花太多时间查看 django-taggit-templatetags 代码,所以请随时用更好的解决方案更新它!
附言:
我在我的 View 中得到一个这样的查询集:
my_queryset = Tag.objects.filter(foo__bar=baz).distinct()
关于django-taggit 从查询集中创建 tagcloud,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783039/