0

我有以下型号(细节省略):

class Author(models.Model):
    name = models.CharField('name', max_length=200, blank=False)    

class Book(models.Model):
    title = models.CharField('title', max_length=200, blank=False)
    author = models.ManyToManyField(Author, blank=False, through='Book_Author')

class Book_Author(models.Model):
    book = models.ForeignKey(Book)
    author = models.ForeignKey(Author)

我想获取标题包含给定查询且作者姓名包含相同查询的所有书籍。

现在我正在做以下事情:

要获取标题包含该单词的所有书籍,我使用以下代码:

for word in words:          
        books = books.filter(Q(title__icontains=word)

要获取作者姓名中包含该词的所有书籍,我使用以下代码:

for word in words:        
        authors = authors.filter(Q(name__icontains=word))        
        for author in authors:      
          for book_author in author.book_author_set.all():
             book = Book.objects.get(id=book_author.book_id)
             results.append(book)

有没有办法改进第二部分?

4

1 回答 1

2

这是简单的方法:

for word in words:          
    books = books.filter(Q(title__icontains=word) )
    books = books.filter(Q(author__name__icontains=word) )

my_books = books.distinct()

*已编辑*

如果您正在查找 title 包含单词或 author 包含单词的书籍,那么查询是:

q_books = None
q_authors = None
for word in words:          
    q_aux = Q(title__icontains=word)
    q_books = (q_books & q_aux ) if bool( q_books) else q_aux
    q_aux = Q(author__name__icontains=word)
    q_authors = (q_authors & q_aux ) if bool( q_authors) else q_aux

my_books = Book.objects.filter( q_books | q_authors ).distinct()

欢迎任何关于更多代码可读性的评论。

于 2012-07-30T11:16:36.647 回答