获取与 Django 中的另一个对象具有最多标签的对象

Get objects with the most tags in common with another object in Django

假设我有一个与标签模型具有多对多关系的图像模型。

给定一张图片,找到与该图片具有超过 x 个标签的所有图片并按标签数量排序的最佳方法是什么?

例如,如果我有一张带有标签的图片 sand, beach, house, water, sea 我想找到让我们说所有具有至少 2 个这些标签的图像,然后按它们有多少来排序。 (基本上是使用共同的标签数量来定义相似性的相似图像函数的实现)

如果可能的话在这里寻找优化的解决方案,使用 Django 的 orm

这应该可以完成工作:

img = Image.objects.first()

Image.objects.filter(tags__in=img.tags.all()).\
  annotate(num_common_tags=Count('pk')).order_by('-num_common_tags')

# To filter out Images with < 2 common tags

Image.objects.filter(tags__in=img.tags.all()).\
  annotate(num_common_tags=Count('pk')).filter(num_common_tags__gt=2).\
  order_by('-num_common_tags')