Django reverse to contains/icontains

django, django-models, django-queryset

Solution

While extras do provide an expanded complex functionality for edge cases, extras should be treated as last resort and likely going to be deprecated at some point.

This can be accomplished using annotate and filtering.

from django.db.models import F, Value, CharField

MyUserModel.objects \
     .annotate(my_name_field=Value('Mr. Peter Johnson', output_field=CharField())) \
     .filter(my_name_field__icontains=F('name'))

Genericized:

from django.db.models import F, Value, CharField

@staticmethod
def reverse_case_insensitive_contains(model, search_field_name: str, search_field_value: str):
    return model.objects \
        .annotate(search_field=Value(search_field_value, output_field=CharField())) \
        .filter(search_field__icontains=F(search_field_name))

Problem

In this question was solved problem for reverse `LIKE` operation in SQL, for example if field name is "Peter Johnson", we could find it by such query: ``` select name from user where "Mr. Peter Johnson" like CONCAT('%', name, '%') ``` Is there any way to do such thing in Django `Q` object (I'm building a big query, so using raw SQL query will not be rational)?

Original source

Related problems