django DB에 이모지 저장하기
요즘 이모지가 잘 나와서
icon을 제작해서 쓰는 것보다 친숙하고
시인성도 좋고 글 맥락에 적절하다.
django github
https://github.com/django/django/blob/main/tests/model_fields/test_textfield.py
를 참고한다.
django/tests/model_fields/test_textfield.py
class TextFieldTests(TestCase): def test_emoji(self): a = modelA(text = '😊') a.save()
이런 식으로 저장하면 됨
내 착각
아래는 나 혼자 착각에 빠져 돌아간 내용이다.
이모지는 unicode이기 때문에 db에 저장되기 전에 문자 변환이 필요하다고 생각했다.
그래서 다음과 같은 방법을 먼저 시도했다.
orm으로 데이터 저장할 때,
a = modelA(text = '')
a.save()를 할 때
a = modelA(text= U&'안녕\+01F92d')
이렇게 저장하면 Nmae U is not defined 오류가 난다.
postgresql 공식 문서를 보면 Unicode를 삽입할 때는
출처
https://towardsdatascience.com/emojis-in-your-data-9a5513ead2dd
https://www.postgresql.org/docs/9.3/sql-syntax-lexical.html
유니코드임을 명시하도록 되어있지만
이는 SQL문 레벨에서의 조작이기 때문에
ORM 레벨에서는 위 코드대로 써야한다.
mysql을 dbms로 사용할 때
mysql에서는 인코딩을 utf8mb4로 설정해야한다고 한다.
mysql의 경우 1byte, 한글은 3byte까지가 최대 문자의 용량이지만
emoji의 경우 표현 할 수 있는 코드를 넘어선다.
UTF-8 encoding may be two, three, or four bytes,
Emoji expressions are 4-bytes, and MySql utf8 encoding is up to 3-bytes,
so the data can't be inserted.
-> Convert Mysql encoding from utf8 to utf8mb4
댓글
댓글 쓰기