1

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 problem is I have a names as a dynamic object and its length is not fixed. What I am thinking would work is if I looped though the names and created a dynamic args object but I am not sure what kind of object that is. I am not sure how exactly to do that, so I am stuck.

If you can help around that, that will be really cool or if you can give me an alternative way to go about the same scenario that would be awesome. Thank you

1

3 Answers 3

2
import operator
names = [...]
query = reduce(operator.or_, [Q(name__icontains=name) for name in names])
results = queryset.complex_filter(query)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

~name__contains==i for i in name~ name__contains is not defined, please add some bit context, thank you
Forget it. As I don't know this stuff, I thought it might be a comparison, but is a keyword argument. As said, resort to this other question, or look at Timmy's answer. Updated this answer, but I probably will delete it soon...
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.