I am trying to migrate to V3 but I cannot figure out how to create a queryset that reproduces the split_words option that exists in V2.
I would appreciate your help!
Like this perhaps ?
word_conditions = Q()
for word in q.split(' '):
word_conditions |= Q(text__icontains=word)
qs = qs.filter(word_conditions)
Perhaps this would help https://docs.djangoproject.com/en/1.9/topics/db/queries/#complex-lookups-with-q-objects
Thank you very much. This is brilliant, fast and pythonic!
I will try to refactor my verbose solution on it.
In an effort to search both in category name and parent category name providing a combined result, I found the following:
class CategoryAutocomplete(autocomplete.Select2QuerySetView):
...
if self.q:
keywords_list = self.q.split(' ')
qs = qs.filter(reduce(
lambda x, y: x & y, [
Q(category_name_en__icontains=word) | Q(base_category_key__base_category_name_en__icontains=word) for word in keywords_list
]
))
I am very happy now that my code is not a mess! I am posting the result in case it can be useful for the docs.
It searches the category and parent category names for each word in combination, in both languages:
class CategoryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Category.objects.none()
qs = Category.objects.all()
if self.q:
word_conditions = Q()
for word in self.q.split():
word_conditions &= Q(
Q(category_name_en__icontains=word) |
Q(base_category_key__base_category_name_en__icontains=word)
) | Q(
Q(category_name_el__icontains=word) |
Q(base_category_key__base_category_name_el__icontains=word)
)
qs = qs.filter(word_conditions)
return qs
You rock :guitar:
Most helpful comment
Like this perhaps ?
Perhaps this would help https://docs.djangoproject.com/en/1.9/topics/db/queries/#complex-lookups-with-q-objects