我正在尝试对模型中的字段内的子字符串进行不区分大小写的搜索。
我的模特:
class doctor(models.Model):
docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary
name = models.CharField(max_length=35)
username = models.CharField(max_length=15)
regid = models.CharField(max_length=15, default="", blank=True)
photo = models.CharField(
max_length=35, default="", blank=True)
email = models.EmailField(default="", blank=True)
phone = models.CharField(max_length=15)
qualifications = models.CharField(
max_length=50, default="", blank=True)
about = models.CharField(
max_length=35, default="", blank=True)
specialities = models.CharField(
max_length=50, default="", blank=True)
department = models.CharField(max_length=50, default="ENT", blank=True)
fees = models.FloatField(default=300.0)
displayfee = models.IntegerField(default=0, blank=True)
slotrange = models.CharField(max_length=50, blank=True)
slotdurn = models.IntegerField(default=10)
breakrange = models.CharField(
max_length=50, default="", blank=True)
slotsleft = models.CharField(
max_length=50, default="", blank=True)
def __str__(self):
return self.name
def Range(self):
return self.slotrange
def listslots(self):
SlotRange = self.slotrange
SlotDurn = self.slotdurn
startime = SlotRange.split('-')[0]
endtime = SlotRange.split('-')[1]
sthr, stmin = SplitTimeString(startime)
enhr, enmin = SplitTimeString(endtime)
print(stamptoday(sthr, stmin))
print(stamptoday(enhr, enmin))
startstamp = stamptoday(sthr, stmin)
endstamp = stamptoday(enhr, enmin)
secdurn = SlotDurn*60
slotlist = []
for sec in range(startstamp, endstamp, secdurn):
enttime = sec + secdurn
myrange = ("%s - %s" % (HumanTime(sec),
HumanTime(enttime)))
slotlist.append(myrange)
return slotlist
在我的mysql数据库的“名称”字段下,是两行,其名称分别为“ Joel”和“ Jaffy Joel”。
当我这样搜索时:
from appointments.models import customer, doctor, appointment
doctor.objects.filter(name__icontains='joel')
输出:
<QuerySet []>
但是当我这样做时:
doctor.objects.filter(name__icontains='Joel')
输出:
<QuerySet [<doctor: Joel>, <doctor: Jaffy Joel>]>
不区分大小写的搜索为什么不适合小写搜索?
答案 0 :(得分:0)
如django docs中所指出,
在MySQL中,数据库表的“排序规则”设置确定是否 精确比较区分大小写。这是数据库设置,不是 Django设置。可以配置您的MySQL表以使用 区分大小写的比较,但需要权衡取舍。欲了解更多 有关此信息,请参见数据库中的排序规则部分 文档。
就我而言,我用
解决了from django.db.models import Q,CharField
from django.db.models.functions import Lower
CharField.register_lookup(Lower, "lower")
doctor.objects.filter(Q(name__lower__contains='joel'))
这方面的提示是django用户邮件列表中的Matthew Pava提供的。