假设您有一个数据库,其中包含在 Djano 应用程序后面运行的用户对象
并且您想使用 django-taggit
来标记用户对象,以便您可以使用一些方便的过滤来检索子组。
此外,您还有一个仪表板,您希望在其中显示有关已用标签的有趣统计信息,以收集有关用户中存在的子组的一些信息。
您将如何访问和显示有关前 X 个标签的信息 在 Django 应用程序中使用?
您如何只访问已过滤的前 X 个标签 用户对象的子组?
最佳答案
虽然 SO 上已经有许多描述类似问题的帖子,但其中大多数描述了解决方法或包含零散的信息。
为了使这些信息更容易找到,我将发布一个简单的纲要,说明如何使用官方支持但 的 django-taggit
功能实现一些基本功能不出现在官方文档中。
How would you access and display information about the top X tags used within the Django app?
为了访问和显示有关 Django 应用程序中使用的顶级标签的信息,您可以使用内置函数 most_common
,如下所示:
top_tags = User.tag.most_common()
这将返回一个查询集,其中包含放置在用户实例上的所有标签,这些标签按最常用的降序排列。
假设我们有 3 个标签:["vegetables", "fruits", "candy"]
并且 10 个用户有一个 fruits
标签,4 个用户有一个 vegetables
标签,只有 1 个用户有 candy
标签返回的订单将是:["fruits", "vegetables", "candy"]
可以像这样访问有关返回标签的更多信息:
for tag in top_tags:
print(tag.name) #the name of the tag
print(tag.num_times) # the number of User objects tagged
此外,如果您只对前 3 个标签感兴趣,那么您可以 像这样访问它们:
top_tags = User.tag.most_common()[:3]
您可以将 3 替换为 X,其中 X 是您要退回的商品数量。
How would you access only the top X tags of an already filtered subgroup of the User object?
自 2016 年 7 月 12 日起,most_common()
函数实际上有一些您可以指定的额外参数。首先,您可以指定一个 min_count
来过滤掉低于特定阈值的顶级标签。作为使用前面示例中的标签的说明:
top_tags = User.tag.most_common()[:3]
返回前面指定的所有三个标签,但使用
top_tags = User.tag.most_common(min_count=2)[:3]
只返回 ["fruits", "vegetables"]
这是因为只有 1 个用户对象被标记为 candy
意味着它低于 min_count
共 2
您可以向 most_common
提供的另一个参数是 extra_filters
,这使您能够提供一个对象,其中包含您希望作为过滤标签依据的额外过滤值。
一个用法示例是:
filtered_users = User.objects.filter(age=20, is_delete=False)
top_tags = User.tag.most_common(
min_count=1, extra_filters={
'user__in': filtered_users
}
)
这里我们创建了一个用户对象的过滤查询集,然后我们将其提供给 extra_filters
参数以将标签搜索限制在特定的子组中
关于django - 如何过滤django-taggit top标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51053595/