The difference between Django __search and __contains

I started learning Django just recently, so please forgive me if this is too new a question for you.

I have a search function implemented in Django. I created a full text index in MySQL DB, and then I have a field in my, say, book model: search_keywordswhere I basically store all the words, including the title and contents of the book. Then my search function does something similar to this:

search_keyword = self.request.GET.get('keywords')
    if search_keyword:
        # '*' is added for cases where user enters only part of the keyword
        qs = qs.filter(keywords__search=search_keyword + '*')

But the above approach does not work, if my search query is "intro", where I know the word / term there, for example, "test.introduction" (if the term "just introduction", then it works fine).

Then when I try this instead:

        qs = qs.filter(keywords__icontains=search_keyword)

he finds "test.introduction", etc.

, , . "__search" ? , "__contains" ( ), , "__search" Django? (, ? - ?

+4
1

, SQL- ... "__contains", "__search" mysql ( django docs) ( PostgreSQL Django ≥ 1.10 - . ).

:

__search

>>> str(Contact.objects.filter(first_name__search='john').query)

'SELECT `contact_contact`.`id`, `contact_contact`.`title`, `contact_contact`.`first_name`, `contact_contact`.`last_name`, `contact_contact`.`user_id`, `contact_contact`.`role_id`, `contact_contact`.`organization_id`, `contact_contact`.`dob`, `contact_contact`.`email`, `contact_contact`.`notes`, `contact_contact`.`create_date` FROM `contact_contact` WHERE MATCH (`contact_contact`.`first_name`) AGAINST (john IN BOOLEAN MODE)'

__contains

>>> str(Contact.objects.filter(first_name__icontains='john').query)

'SELECT `contact_contact`.`id`, `contact_contact`.`title`, `contact_contact`.`first_name`, `contact_contact`.`last_name`, `contact_contact`.`user_id`, `contact_contact`.`role_id`, `contact_contact`.`organization_id`, `contact_contact`.`dob`, `contact_contact`.`email`, `contact_contact`.`notes`, `contact_contact`.`create_date` FROM `contact_contact` WHERE `contact_contact`.`first_name` LIKE %john% '
+3

Source: https://habr.com/ru/post/1534567/


All Articles