Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lower() in django model

This is my query

SELECT * FROM `music` where lower(music.name) = "hello"

How can I send this query with django

I tried this but it didn't add lower in the query

>>> Music.objects.filter(name__iexact="hello")
(0.144) SELECT `music`.`id`, `music`.`name`, `music`.`artist`, `music`.`image`, `music`.`duration`, `music`.`release_date`, `music`.`is_persian` FROM `music` WHERE `music`.`name` LIKE 'hello' LIMIT 21; args=('hello',)
<QuerySet []>
like image 802
Arian Avatar asked Sep 15 '25 21:09

Arian


1 Answers

You can use Lower database function as below.

>>> from django.db.models.functions import Lower
>>> lower_name_music = Music.objects.annotate(lower_name=Lower('name'))
>>> lower_name_music.filter(lower_name__iexact="hello")
  • First statement is to import the database function.

  • Second statement is to add calculated column named lower_name using Lower function on name column. At this time database is not yet been queried.

  • Third statement is to filter using the calculated column. As this statement prints out result, a query is actually executed against database.

like image 157
Hai Lang Avatar answered Sep 17 '25 09:09

Hai Lang