如何找到具有最相似字段的对象?

问题描述

这是我定义的模型:

class Book(models.Model):

    authors = models.ManyToManyField(to='Author')
    category = models.ForeignKey(to='Category')
    tags = models.ManyToManyField(to='tags')

    # some other fields

如何找到与特定对象在这三个领域(作者、类别、标签)最相似的十本书?

例如,如果我有以下图书对象:

Book:
  title: Harry Potter
  authors: J. K. Rowling
  category: Novel
  tags: Fantasy Fiction,Drama,Young adult fiction,Mystery,Thriller

我想将具有最匹配的作者、类别和标签字段的书对象返回到哈利波特书。

我的问题几乎类似于 this,但我正在寻找更简洁的答案。

解决方法

我认为你需要导入 Q 从 django.db.models 导入 Q

Book.objects.filter(Q(tags='Fantasy Fiction')|Q(tags='Young adult fiction')|Q(tags ='Mystery'),category='Novel',authors='J. K. Rowling')