I'm using Python 3.7 and Django. Is there a way I can rewrite the below so taht I just execute one query instead of a bunch?
def get_articles_with_words_in_titles(self, long_words):
result = {}
for word in long_words:
qset = Article.objects.filter(title__icontains=word.lower())
result.extend( qset )
return result
I want to get a unique list of the Article objects that have at least one of the words in them.
Yes, you can iterate over it using these libraries like so:
from functools import reduce
from django.db.models import Q
import operator
qset = Article.objects.filter(reduce(operator.or_, (Q(title__icontains=x) for x in long_words)))