问题
I have a model:
class Trophy(models.Model):
server = models.CharField(max_length=191, blank=True)
title = models.CharField(max_length=191, blank=True)
note = models.TextField(blank=True)
badge = models.CharField(max_length=191)
badge - is a field for unicode characters like 🐲 or 💎 or 🔝 or ☔️ or 💯 etc...
I have three trophies in database:
- Dragon (badge=🐲)
- Antiaircrafter (badge=☔️)
- Diamond player (badge=💎)
I have not problem to get trophy with badge ☔️:
trophy = Trophy.objects.get(badge=u"☔️")
But I can't get 🐲 or 💎:
trophy = Trophy.objects.get(badge=u"🐲")
MultipleObjectsReturned: get() returned more than one Trophy -- it returned 2!
And one more thing: I can't see 🐲 and 💎 in MySQL Workbench (only "?") untill run:
SET NAMES utf8mb4;
Any idea how to work with utf8mb4 in django queries?
回答1:
Fixed by adding OPTIONS for db settings in django settings.py:
'OPTIONS': {
'charset': 'utf8mb4',
'use_unicode': True,
'init_command': "SET NAMES utf8mb4;",
}
And create db with command
CREATE DATABASE feofun_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
来源:https://stackoverflow.com/questions/45234897/filter-django-query-by-unicode-characters-or-etc