Concatenating filter requests with a loop in django
<p>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):</p>

<pre><code>#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]))
</code></pre>

<p>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</p>

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

<p>I understand that the <code>filter()</code> 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.</p>

<p>You probably want to use the <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct" rel="nofollow">distinct</a> filter.</p>

python django