0

I have a list of strings that I need to determine if they are present in my model names. Currently I am using a series of if and elif statements to determine how many strings are in my list of strings then execute a filter request to my database like this (this works but is extremely inefficient as I am constantly repeating myself):

#example if my list contained only 2 strings

if len(listOfStrings) == 2:


    queryResults = MyModel.objects.filter(Q(name__contains=listOfStrings[0])|Q(name__contains=listOfStrings[1]))

Then I notify the client based on the result of these queries. If I test the strings against my models each individually I might get the same models (because some model names contain all three or two strings) then notify the client twice. So I would think to solve this problem using a for loop like so

listOfStrings = {"string1","string2","string3"}
queryResults = ""
for string in listOfStrings:
    queryResults += MyModel.objects.filter(name__contains=string)

I understand that the filter() method is lazy and doesn't execute right away and that this python logic is most likely wrong. But how do I concatenate filter requests in order to avoid duplicate model results.

  • check this [post](http://stackoverflow.com/questions/7088173/how-to-query-model-where-name-contains-any-word-in-python-list) might be helpful – kt14 Aug 29 '16 at 15:23

1 Answers1

1

You probably want to use the distinct filter.

vincent
  • 1,370
  • 2
  • 13
  • 29