我的目标是使用用户通过搜索表单发送的值从books表返回行.搜索表单包含多个字段"作者"、"ISBN"和"标题".
NB: In the code, the author field is a char, but converted to ID based on authors name due to foreign key relation.
在这段代码中,有一个get请求被转换为Dictionary,并被转换为允许它从books表中查询数据.
def search(request):
form = BooksForm()
if request.method == 'GET':
# convert get request to dictionary
book_search = dict(request.GET)
print("data before cleaning", book_search)
#get the name from the dictionary get request
author_name =request.GET['author']
#get the author id from the author table
author = Author.objects.filter(full_name__contains=author_name).values()
#get author_id from author queryset
author_id = author[0]['id']
#update the dict with the author id to allow search in books models (foreing key)
book_search['author'] = author_id
print("data after cleaning",book_search)
result_set = Book.objects.filter(**book_search)
print("book search queryset",result_set)
问题: