Filter queryset from filename field based on two words that appear one after the other Django

67 views Asked by At

I have a Files table, which contains various fields, one of which is a filename. Within each one of the files in this table, there is a specific file that I'd like to retrieve, which is basically a terms and conditions. This filename will always have the words 'terms' and 'conditions' within the filename itself, and it will always be in that order. However, there could be other words surrounding both 'terms' and 'conditions'.

For example, a filename could be 'my new terms and conditions' or 'my even better terms blah blah conditions'.

I'm trying to write a queryset that will retrieve such a file using Regex but I'm not able to do so. So far, I have something like:

file = Files.objects.filter(
    Q(filename__iregex=r'(^|\W){}.*({}|$)'.format("term", "condition"))
).first()

but this doesn't work.

1

There are 1 answers

0
Sardorbek Imomaliev On BEST ANSWER

You have few options here.

  1. Filter twice, this will create subquery underneath

    file = Files.objects.filter(filename_icontains="term").filter(filename_icontains="condition").first()
    
  2. You could achieve this via regex, as you've tried. I think simplifying it should work

    file = Files.objects.filter(filename__iregex=r"^.*term.*condition.*$").first()