0

I have a list of strings (say s = ['1995','1996','1997']). I need to find all rows in my database, where some column's first four characters match any item in that list (For example 1995-01-01 or 1996-05-04).

Found __in, but it finds exact matches.

César
  • 9,939
  • 6
  • 53
  • 74
wishiknew
  • 384
  • 1
  • 11

1 Answers1

4
import operator
years = ['1995','1996','1997', ...]
query = reduce(operator.or_, [Q(year__startswith=year) for year in years])
results = queryset.filter(query)

This would give you SQL similar to WHERE year LIKE '1995%' OR year LIKE '1996%' ...; which mightn't perform well given your dataset. You might get better performance writing the SQL manually using extra()

Strangely, I just answered another question previously with almost the exact same code!

Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177