我在 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/