Filter django query by unicode characters 🐲 or 💎 etc

时光怂恿深爱的人放手 提交于 2019-12-13 16:10:35

问题


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:

  1. Dragon (badge=🐲)
  2. Antiaircrafter (badge=☔️)
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!