How to make a "LIKE" in a DJANGO ORM query?

4

To make a query to get the data exactly in Django, I use filter , like this:

usuarios = Usuarios.objects.filter(nome='Jonh')

This will generate a SQL similar to:

SELECT * FROM usuarios wHERE nome = 'Jonh'

Since I've been using Django for a short time, I'd like to know how I would do to make a LIKE .

The database I'm using is Mysql.

    
asked by anonymous 15.02.2018 / 14:03

2 answers

5

There are a few ways to run this query:


Case sensitive

  • Using contains : usuarios = Usuarios.objects.filter(nome__contains='Jonh')

    • SQL: SELECT * FROM usuarios WHERE nome LIKE '%Jonh%';
  • Using startswith : usuarios = Usuarios.objects.filter(nome__startswith='Jonh')

    • SQL: SELECT * FROM usuarios WHERE nome LIKE 'Jonh%';
  • Using endswith : usuarios = Usuarios.objects.filter(nome__endswith='Jonh')

    • SQL: SELECT * FROM usuarios WHERE nome LIKE '%Jonh';

  • Case insensitive

  • Using icontains : usuarios = Usuarios.objects.filter(nome__icontains='Jonh')

    • SQL: SELECT * FROM usuarios WHERE nome ILIKE '%Jonh%';
  • Using istartswith : usuarios = Usuarios.objects.filter(nome__istartswith='Jonh')

    • SQL: SELECT * FROM usuarios WHERE nome ILIKE 'Jonh%';
  • Using iendswith : usuarios = Usuarios.objects.filter(nome__iendswith='Jonh')

    • SQL: SELECT * FROM usuarios WHERE nome ILIKE '%Jonh';

  • The use of double underscore (__), defined by the constant LOOKUP_SEP is used by ORM - object-relational mapping - for generating SQL queries by separating the variable from the search command, as in the LIKE example: nome__iendswith='Jonh' interpreted for nome ILIKE 'Jonh%' .

        
    15.02.2018 / 14:58
    3

    I've researched a bit and found this here.

    You can do this as follows:

    Usuarios.objects.filter(nome__contains = "Jonh")
    

    And according to the answer itself, __contains is case sensitive, and __icontains can be used to ignore the case (upper / lower case)

        
    15.02.2018 / 14:08