Paulo Fabrício
Paulo Fabrício

Reputation: 329

Django queryset where a field values are in a list

I need to make a query that returns all rows where the field subject values exist in a list. I don't matter with sensitive case, but the values should be exact with the ones in the list.

I'm using:

my_list = ["Others", "Entertainment"]
results = MyObject.objects.filter(subject__iregex=r"(" + "|".join(my_list) + ")")

This is the solution from the topic Django query case-insensitive list match but as result I have rows where:

subject = "others tv series"

and I just want rows like:

subject = "others"

I need something like iexact and in mixed.

Thanks!

Upvotes: 1

Views: 348

Answers (1)

heemayl
heemayl

Reputation: 42017

You need to add the start and end of line specifies in Regex, ^ and $, respectively:

subject__iregex=r"^(" + "|".join(my_list) + ")$"

I find str.format to be more readable (for Python 3.6+ also look at f-strings):

'^({})$'.format('|'.join(my_list))

As we are not referring to the captured group later-on, we can make the group non-capturing:

'^(?:{})$'.format('|'.join(my_list))

Upvotes: 1

Related Questions