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

glglgl
  • 89,107
  • 13
  • 149
  • 217
Aleister
  • 163
  • 9
  • 1
    possible duplicate of [Django : How to Query model where name contains any word in python list?](http://stackoverflow.com/questions/7088173/django-how-to-query-model-where-name-contains-any-word-in-python-list) – glglgl Dec 12 '12 at 10:55

3 Answers3

2
import operator
names = [...]
query = reduce(operator.or_, [Q(name__icontains=name) for name in names])
results = queryset.complex_filter(query)
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
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.

Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • ~name__contains==i for i in name~ name__contains is not defined, please add some bit context, thank you – Aleister Dec 12 '12 at 11:02
  • 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](http://stackoverflow.com/q/7088173/296974), or look at [Timmy's answer](http://stackoverflow.com/a/13838553/296974). Updated this answer, but I probably will delete it soon... – glglgl Dec 12 '12 at 11:29
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)
Aleister
  • 163
  • 9