Django use __icontains with __in for field lookup
In Django, __icontains
and __in
are field lookups to the QuerySet methods. __icontains
is a case-insensitive containment test, and __in
means that the field is in a given iterable. So I would like to do the following lookup:
keywords = ['How', 'to', 'setup', 'PrismJS', 'and', 'Autoloader', 'plugin', 'with', 'Nuxt', '3?']
#Possible keywords of title
Writings.objects.filter(title__icontains__in=arr)
Unfortunately, we can not combine field lookups in Django.
To implement our desire, we can use Q()
objects (see Complex lookups with Q objects), and combine them with |
operator by looping.
from django.db.models import Q
def title_matching(merchants):
"""
Return a queryset for writings whose titles contain case-insensitive
matches for any of the `keywords`.
"""
q = Q()
for key in keywords:
q |= Q(title__icontains = key)
return Writings.objects.filter(q)
Similarly, we can use the same way to combine __iexact
with __in
.
There is no comment, let's add the first one.