简体   繁体   English

如何在 Django 中进行此搜索查询?

[英]How to make this search query in django?

my search query works fine when i fill the book and chapter in my searchfield.当我在搜索字段中填写书籍和章节时,我的搜索查询工作正常。 but when i only fill in the book i get an error.但是当我只填写这本书时,我得到了一个错误。 Can somebody help me?有人可以帮助我吗?

Request Method: GET Request URL: http://127.0.0.1:8000/search/?q=genesis Django Version: 3.0 Exception Type: ValueError Exception Value:请求方法:GET 请求 URL: http : //127.0.0.1 :8000/search/?q= genesis Django 版本:3.0 异常类型:ValueError 异常值:
not enough values to unpack (expected 2, got 1)没有足够的值来解包(预期为 2,得到 1)

def get_queryset(self): 
    query = self.request.GET.get('q')
    book, chapter = query.split()

    object_list = Verse.objects.filter(
        Q(book__icontains=book) & Q(
            chapter__exact=chapter))

    return object_list

This does not work, since then there is only one word, and hence query.split() will return a singleton list.这不起作用,因为只有一个词,因此query.split()将返回一个单例列表。

def get_queryset(self): 
    query = self.request.GET.get('q')
    object_list = Verse.objects.all()
    if query:
        query = query.split()
        object_list = object_list.filter(book__icontains=query[0])
        if len(query) > 1:
            object_list = object_list.filter(chapter=query[1])
    return object_list

I'm however not convinced that splitting by a space is a good idea here.然而,我不相信在这里用空格分割是个好主意。 If the book name contains spaces, then .split() will thus split the title, and you will take the second word as chapter .如果书名包含空格,则.split()将因此拆分标题,您将第二个单词作为chapter You might want to split on an identifier like a colon ( : ).您可能想要拆分一个标识符,如冒号 ( : )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM