mysql - 奇怪的不区分大小写的选择行为 Django + mysql

标签 mysql django

我在 Django 中有简单的模型:

class Tag(Model):
    name = CharField(unique=True, max_length=50)

当我这样做时:

t = 'Ansible'
print("Want tag: " + t)
tg, created = Tag.objects.get_or_create(name=t)
print("Got tag: " + tg.name)
print("Query: {}".format(Tag.objects.filter(name=t).query))
print("Query result: {}".format(Tag.objects.filter(name=t).first().name)) 

我得到结果:

Want tag: Ansible
Got tag: ansible
Query: SELECT `main_tag`.`id`, `main_tag`.`slug`, `main_tag`.`name`, `main_tag`.`added_time`, `main_tag`.`public_tips_count`, `main_tag`.`private_tips_count` FROM `main_tag` WHERE `main_tag`.`name` = Ansible
Query result: ansible

我使用Django==1.10.3

# mysql --version
mysql  Ver 14.14 Distrib 5.5.34, for debian-linux-gnu (armv7l) using readline 6.2

我期望什么?

我期望 get_or_create 它将创建名为 Ansible 的新标签,但它返回一些名为 ansible 的现有标签

最佳答案

Mysql开箱即用的情况是insensitive 。此行为与 django 无关。

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

您可以make it case sensitive在系统、数据库、表甚至列级别。

关于mysql - 奇怪的不区分大小写的选择行为 Django + mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41362149/

相关文章:

python - Django:从另一个应用程序导入 View

django - Dockerized Nginx 和 Django,如何提供静态文件

javascript - 获取 TypeError : Cannot call method 'releaseConnection' of null in mysql node. js

mysql - 优化关联查询

mysql - 为什么当我查询更多列时,MYSQL 不使用同一查询的索引?

python - Heroku django 没有这样的应用程序

php - Yii2:无法从表单发送电子邮件

mysql - 当前时间,但昨天

python - 使用 Windows 在 apache 上部署多个 Django 项目

Django 模板变量值与字符串文字比较失败