Case-insensitive find_or_create_by_whatever

后端 未结 4 1102
天命终不由人
天命终不由人 2021-01-12 15:58

I want to be able to do Artist.case_insensitive_find_or_create_by_name(artist_name)[1] (and have it work on both sqlite and postgreSQL)

What\'s the best

4条回答
  •  感动是毒
    2021-01-12 16:20

    You have to create an index based on the database.

    postgreSQL

    Create a lower case index on artist_name column.

    CREATE INDEX lower_artists_name ON artists(lower(artist_name))
    

    mySQL

    Searches are case insensitive

    sqlLite

    Create a index on artist_name column with collate parameter

    CREATE INDEX lower_artists_name ON artists( artist_name collate nocase)
    

    Now you can use find_or_create in a DB independent manner:

    find_or_create_by_artist_name(lower(artist_name))
    

    Reference

    PostgreSQL: Case insensitive search

    sqlLite: Case insensitive search

提交回复
热议问题