[Answered ]-Django QuerySet filter()

1👍

Yes, you can’t use properties and function’s name in filter

This can do either using list compression or generator expression as follows:

# for single File object 
sr_file = next(
          (f for f in File.objects.filter() if keyword in f.filename()), 
          None)

or

# for: all File objects contains keywords in their file path: 
sr_files = [f for f in File.objects.filter() if keyword in f.filename()]

1👍

Return the part after the last / in a path is what os.path.basename does. So you could use regex lookup

import re
File.objects.filter(uploaded_file__regex='[^/]*{}[^/]*$'.format(re.escape(keyword)))

Or simply

files = File.objects.filter(uploaded_file__contains=keyword)
# Then discard false matches
files = (f for f in files if keyword in f.filename())
👤okm

Leave a comment