dan-klasson
dan-klasson

Reputation: 14190

Django Querysets & dynamic string filtering

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?

Upvotes: 1

Views: 80

Answers (2)

Mark Lavin
Mark Lavin

Reputation: 25164

__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.

Upvotes: 0

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48982

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)

Upvotes: 2

Related Questions