How to get similar projects based on tags in Django

为君一笑 提交于 2019-12-08 12:39:28

问题


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)

回答1:


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]

Or, broken down in steps:

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

The logic goes as follows:

  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].


来源:https://stackoverflow.com/questions/7750232/how-to-get-similar-projects-based-on-tags-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!