Skip to content Skip to sidebar Skip to footer

Creating Dynamic Objects With | Separator Python

What I want is to solve is something like this names = ['Aleister', 'Matovu'] args = (Q(name__contains=name[0])|Q(name__contains=name[1])) queryset.complex_filter(args) What the

Solution 1:

import operator
names = [...]
query = reduce(operator.or_, [Q(name__icontains=name) for name in names])
results = queryset.complex_filter(query)

Solution 2:

I do not know what Q is in this case, but maybe

import operator
qq = [Q(name__contains=i) for i in name)]
args = reduce(operator.or_, qq)

might help. But as this is the same as Timmy wrote, don't upvote me, but him.

If not, see at this question here.


Solution 3:

Here is a pretty satisfying solution. If it is ever of any help to anyone

http://bradmontgomery.blogspot.com/2009/06/adding-q-objects-in-django.html

q = Q(content__icontains=term_list[0]) | Q(title__icontains=term_list[0])
for term in term_list[1:]:
    q.add((Q(content__icontains=term) | Q(title__icontains=term)), q.connector)

stories = stories.filter(q)

Post a Comment for "Creating Dynamic Objects With | Separator Python"