我如何让 Django 对我的 MySql 5.7 db 进行 运行 不区分大小写的查询?

How do I get Django to run a case-insensitive query against my MySql 5.7 db?

我正在使用 Django 2.0 和 Python 3.7。我有这个模型和经理,用于尝试按名称、区分大小写地查找我的模型。支持数据库是 MySql 5.7.

class CoopManager(models.Manager):
    ...

    # Look up coops by a partial name (case insensitive)
    def find_by_name(self, partial_name):
        queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True)
        print(queryset.query)
        return queryset


class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

不幸的是,当实际创建查询时,Django 似乎没有采取任何措施来解决不区分大小写的问题。这是一个示例查询,结果 ...

SELECT `maps_coop`.`id`, `maps_coop`.`name`, `maps_coop`.`type_id`, `maps_coop`.`address_id`, `maps_coop`.`enabled`, `maps_coop`.`phone`, `maps_coop`.`email`, `maps_coop`.`web_site` FROM `maps_coop` WHERE (`maps_coop`.`name` LIKE %res% AND `maps_coop`.`enabled` = True)

我需要做哪些更改才能让 Django 以不区分大小写的方式对我的 MySql 数据库执行查询?

编辑: 这是 "show create table ..."

的 MySql 输出
| maps_coop | CREATE TABLE `maps_coop` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) COLLATE utf8_bin NOT NULL,
  `enabled` tinyint(1) NOT NULL,
  `phone` varchar(128) COLLATE utf8_bin DEFAULT NULL,
  `email` varchar(254) COLLATE utf8_bin DEFAULT NULL,
  `web_site` longtext COLLATE utf8_bin NOT NULL,
  `address_id` int(11) DEFAULT NULL,
  `type_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `maps_coop_address_id_f90898f3` (`address_id`),
  KEY `maps_coop_type_id_982652ce_fk_maps_cooptype_id` (`type_id`),
  CONSTRAINT `maps_coop_address_id_f90898f3_fk_address_address_id` FOREIGN KEY (`address_id`) REFERENCES `address_address` (`id`),
  CONSTRAINT `maps_coop_type_id_982652ce_fk_maps_cooptype_id` FOREIGN KEY (`type_id`) REFERENCES `maps_cooptype` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=933 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |

您必须将 MySQL database/table 排序规则更改为 utf8_unicode_ciutf_unicode_ci;末尾的 ci 缩写代表 "case i不敏感.

还要检查这个 Q/A utf8_bin vs. utf_unicode_ci