我有 3 个模型:
class Author(models.Model):
title = CharField()
class Genre(models.Model):
title = CharField()
class Book(models.Model):
title = CharField()
author = ManyToManyField(Author)
genre = ManyToManyField(Genre)
我有一个包含所有流派和作者的复选框表单(多选),其中复选框值是项目(流派或作者)ID。
目的:显示具有选定作者或流派的书籍(不重复)
我可以通过两种方式做到这一点:
第一种方式:
if request.POST:
book_list = Book.objects.all() #get all books from db
books = []
request_list = request.POST.getlist('genre') #select list of genres in request
for item in request_list:
add_book = report_list.filter(genre=r_request) #queryset of book filtered by each genre
books.append(add_book)
book_list = book_list.exclude(genre=item)
request_list = request.POST.getlist('author') #select list of authors in request
for item in request_list:
add_book = report_list.filter(author=item) #queryset of book filtered by each author
books.append(add_book)
book_list = book_list.exclude(author=item)
return ...
'books': books
但是当我选择很多作者和流派时,这种方式很慢,因为排除很慢。
第二种方式:
删除book_list = book_list.exclude(...)并应用模板标签 {% ifchanged book.id %}
但是我认为,当我在请求结果中获得 1000 多本书时,这也会很慢(书)
如何快速显示选定作者和类型的书籍?