虽然 SO 上已经有许多帖子描述了类似的问题,但其中大多数描述了解决方法或包含分散的信息。
为了使这些信息更容易找到,我将发布一个简单的概要,说明如何使用以下功能来实现一些基本的东西django-taggit
得到官方支持,但not存在于官方文档中。
您将如何访问和显示有关前 X 个标签的信息
在 Django 应用程序中使用?
为了访问和显示有关 Django 应用程序中使用的顶级标签的信息,您可以使用内置函数most_common
像这样:
top_tags = User.tag.most_common()
这将返回一个查询集,其中包含放置在 User 实例上的所有标签,按最常用的降序排列。
假设我们有 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 是您想要退回的商品数量。
如何仅访问已过滤的前 X 个标签
User 对象的子组?
自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 个 User 对象被标记为candy
这意味着它低于min_count
of 2
您可以提供的附加参数most_common
is 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
}
)
在这里,我们创建了一个经过过滤的 User 对象查询集,然后将其提供给extra_filters
将标签搜索限制到特定子组的参数