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.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.