1

It seems that __in is only suitable for integers. I am trying to filter by strings.

I've tried this but it does not work.

    groups = ['foo', 'bar'] 
    args = []
    for group in groups:
        args.append(Q(name=group))
    group_ids = Group.objects.filter(*args)

What is the preferred way to dynamically filter a Django queryset using strings?

3
  • 2
    What makes you say __in is only suitable for integers? It works just fine for strings. Commented Feb 2, 2014 at 17:15
  • @Mark is correct. See my answer below if you need something other than an exact match (e.g. iexact, contains). Commented Feb 2, 2014 at 17:21
  • @Mark: My bad. You are right. If you post your comment as an answer I will accept it. Commented Feb 2, 2014 at 17:27

2 Answers 2

2

Your query is doing an and of all those values, and I assume you want an or? Try:

query = Q(name=groups[0])
for group in groups[1:]:
    query |= Q(name=group)

group_ids = Group.objects.filter(query)
Sign up to request clarification or add additional context in comments.

Comments

0

__in can be used for strings as it translates to a SQL IN operation. Whether or not it is case-sensitive my depend on your table/column collation.

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.