如何基于Django中的标签获取类似的项目 [英] How to get similar projects based on tags in Django

查看:93
本文介绍了如何基于Django中的标签获取类似的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有 Project Tag 模型,它们之间存在多对多关系。我想在每个项目的页面上列出3个其他项目,这些项目具有最多的共同标签。如何执行此查询?

I have Project and Tag models in my application with a many-to-many relationship between them. On each project's page I want to list 3 additional projects that have the most tags in common with it. How can I perform this query?

class Tag(models.Model):
  name = models.CharField(max_length=300)

class Project(models.Model):
  name = models.CharField(max_length=300)
  ...
  tags = models.ManyToManyField(Tag)


推荐答案

可以将所有内容打包在一起行:

It is possible to pack it all in one line:

Project.objects.filter(tags__in=current_project.tags.all()).annotate(Count('name')).order_by('-name__count')[:3]

或者,按步骤细分:

tags = current_project.tags.all()
matches = Project.objects.filter(tags__in=tags).annotate(Count('name'))
results = matches.order_by('-name__count')[:3]

逻辑如下:


  1. current_project

  2. 过滤器选择所有项目t帽子具有与当前项目相同的标签。

  3. 注释在返回值中添加了一个变量,用于计算相似的名字。当匹配多个标签的项目被多次返回时,该值表示匹配的数量。

  4. 结果按带注释的 name__count 变量。要获得前3个结果,请在列表中使用 [:3]

  1. current_project is the instance of the project you want the relations for.
  2. The filter selects all projects that have tags that are the same as the current project.
  3. The annotate adds a variable to the return values that counts the number of similar names. As projects that match multiple tags are returned multiple times, this value in indicative for the number of matches.
  4. The results are sorted on the annotated name__count variable. To get the top 3 results, the list is capped using [:3].

这篇关于如何基于Django中的标签获取类似的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆