1

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!

Paulo Fabrício
  • 319
  • 3
  • 17

1 Answers1

1

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))
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • 1
    @PaulozOiOzuLLuFabrício It builds the Regex correctly. Check out for any whitespaces around the `subject` field's value. Also you are using `__iregex`, right? – heemayl Aug 15 '18 at 21:09
  • Yeah! It's ok! In the question I used the field subject, but in my code I need the field category, LOL. I changed my code and it works like a charm! Thanks, man! – Paulo Fabrício Aug 15 '18 at 21:22
  • 1
    @PaulozOiOzuLLuFabrício it happens! Glad I could help :) – heemayl Aug 15 '18 at 21:23