How to get similar projects based on tags in Djang

2019-06-12 09:05发布

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条回答
女痞
2楼-- · 2019-06-12 09:40

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].
查看更多
登录 后发表回答