问题
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:
current_project
is the instance of the project you want the relations for.- The
filter
selects all projects that have tags that are the same as the current project. - 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. - 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