Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does this operator means in django `reduce(operator.and_, query_list)`

I am reading this questions

Constructing Django filter queries dynamically with args and kwargs

I am not able to get what does this operator do

filter(reduce(operator.or_, argument_list))

or this

filter(reduce(operator.and_, query_list))

like image 879
user194932147 Avatar asked Apr 18 '13 07:04

user194932147


People also ask

What is reduce in Django?

reduce is a built-in function similar to the code below: def reduce(func, items): result = items.pop() for item in items: result = func(result, item) return result. Where func is a user defined function. operator.or_ is a python standard library function that wraps the or operator.

What does _() mean in Django?

_ is usually a macro/function from gettext, it means the argument is a localized string. this is not limited to Django or Python. in fact gettext is originally a package for C programs, ported to many other languages over the years.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.


1 Answers

filter is a regular method of Django Model Manager, so there is nothing to explain.

reduce is a built-in function similar to the code below:

def reduce(func, items):
    result = items.pop()
    for item in items:
        result = func(result, item)

    return result

Where func is a user defined function.

operator.or_ is a python standard library function that wraps the or operator. It is similar to this code:

def or_(a, b):
    return a | b

For example:

reduce(operator.or_, [False, False, True])

Will return True.

In your example context, the or and the and operators are overloaded and therefore it should return a new query combined of smaller parts all concatenated by or or and operator.

like image 166
Yossi Avatar answered Sep 22 '22 16:09

Yossi