0

This is the model I have defined:

class Book(models.Model):

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

    # some other fields

How can I find ten books that are most similar in these three fields (authors, category, tags) to a specific object?

For example if I have the following book object:

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

I'd like to return the book object with the most matching fields of authors and category and tags to the Harry Potter book.

My question is almost like this, but I am looking for a cleaner answer.

1 Answers1

0

I think You need to import Q from django.db.models import Q

Book.objects.filter(Q(tags='Fantasy Fiction')|Q(tags='Young adult fiction')|Q(tags ='Mystery'),category='Novel',authors='J. K. Rowling')
lord stock
  • 1,191
  • 5
  • 32