·

Django use __icontains with __in for field lookup

Published at 2024-06-28 00:39:14Viewed 263 times
Professional article
Please reprint with source link

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.

0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Vertically aligning CSS :before and :after content

I am trying to centre the link with the image, but can't seem to move the content vertically in any way.<h4>More Information</h4> <a href="#" class="pdf">File Name</a>The icon is 22 x 22px.pdf { font-size: 12px; } .pdf:before { padding:0 5px 0 0; content: url(../img/icon/pdf_small.png); } .pdf:after { content: " ( .pdf )"; font-size: 10px; } .pdf:hover:after { color: #000; }

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved