Skip to content

Instantly share code, notes, and snippets.

@channprj
Created October 28, 2024 10:16
Show Gist options
  • Save channprj/77c10a81dba6bd82e6f751b677218854 to your computer and use it in GitHub Desktop.
Save channprj/77c10a81dba6bd82e6f751b677218854 to your computer and use it in GitHub Desktop.
DB Collate with Django ORM
# Use ko_KR.utf8 for lower version of Postgres
# ex: select * from sample_table order by "name" COLLATE "ko-KR-x-icu";
ko_name = Func("name", function="ko-KR-x-icu", template='(%(expressions)s) COLLATE "%(function)s"')
queryset = queryset.order_by(ko_name.asc())
@channprj
Copy link
Author

channprj commented Oct 28, 2024

-- Manual control with SQL

-- Check current collates:
SELECT collname FROM pg_collation WHERE collname like '%KR%' ORDER BY collname;
SELECT datname, datdba, encoding, datcollate, datctype FROM pg_database;

-- Change DB collate:
UPDATE pg_database SET datcollate = 'ko_KR.utf8' WHERE datname = 'db_name';

-- Set collate in select query:
SELECT * FROM sample_table ORDER BY "name" COLLATE "ko-KR-x-icu";

-- ...or you can manually change collate below:
ALTER TABLE sample_table ALTER COLUMN name SET DATA TYPE text COLLATE "ko-KR-x-icu";

-- Rollback:
ALTER TABLE sample_table ALTER COLUMN name SET DATA TYPE text COLLATE "en_US";

-- Test it
SELECT * FROM sample_table ORDER BY "name" ASC;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment