简体   繁体   中英

How to use Q objects in Django

I am trying to understand how to make a simple search form for a website in Django. After some google search and few failures to do it on my own I ended up with the following code in views.py where 'q' is value retrieved from the form:

class BookSearchListView(BookListView):
    def get_queryset(self):
        result=super(BookSearchListView, self).get_queryset()
        query=self.request.GET.get('q')
        if query:
            query_list=query.split()
            result=result.filter(reduce(operator.and_,(Q(title__icontains=q) for q in query_list))) 
        return result

I already understand how it works and why there is reduce and operator.and_ (I mean, I think I understand). But I do not understand why a simple result=result.filter(Q(somedbfield_icontains=q)) returns and error (even if input is a single word). I also don't understand why reduce needs to get bitwise value?

why a simple result.filter(Q(somedbfield_icontains=q)) returns and error

The simplest variant would be result.filter(somedbfield__icontains=q) Q isn't needed there, Q is used to extend your filtering with logic operators (and, or, not). Also, notice the double underscore before icontains .

why reduce needs to get bitwise value?

It dosen't

reduce is used to apply any function to an iterable of arguments:

operator.add(1, 2) is the same as 1 + 2

reduce(operator.add, (1, 2, 3, 4, 5)) is the same as ((((1 + 2) + 3) + 4) + 5)

Works roughly like this:

def reduce(function, iterable):
    it = iter(iterable)
    value = next(it)

    for element in it:
        value = function(value, element)

    return value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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