V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
larkifly
V2EX  ›  Python

django 数据库查询 filter 如何区分大小写

  •  
  •   larkifly · 2014-10-12 14:43:07 +08:00 · 8735 次点击
    这是一个创建于 3474 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我试了__exact方法,但是没用,依然没有区分大小写
    8 条回复    2014-10-13 16:13:49 +08:00
    zeq
        1
    zeq  
       2014-10-12 16:06:16 +08:00
    你的代码是怎样的
    raquelken
        2
    raquelken  
       2014-10-12 17:34:39 +08:00
    @larkifly
    iexact
    larkifly
        3
    larkifly  
    OP
       2014-10-13 10:31:14 +08:00
    @zeq
    usable = CarCardList.objects.filter(car_card__iexact=code)
    usable = CarCardList.objects.filter(car_card__exact=code)

    class CarCardList(models.Model):
    car_card = models.CharField(max_length=255, unique=True)
    is_used = models.BooleanField(default=False)
    get_from = models.ForeignKey(Merchant)
    used_time = models.IntegerField(null=True)
    user = models.ForeignKey(User, null=True)
    def __unicode__(self):
    return self.car_card

    这两个方法都没用,环境是windows mysql
    zeq
        4
    zeq  
       2014-10-13 11:16:23 +08:00   ❤️ 1
    这是因为mysql的查询默认是不区分大小写的,你可以在匹配语句钱加上 BINARY 来区分大小写,例如

    SELECT * WHERE BINARY title='django';

    可以供你参考的一个方法是:

    CarCardList.objects.extra(where=['binary car_card=%s'], params=[code])

    https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra
    y10n
        5
    y10n  
       2014-10-13 11:18:50 +08:00
    数据库看看呢

    如果类似 utf8_general_ci 改成 utf8_general_cs
    __exact用的是=
    __iexact用的是LIKE,效率也考虑下哦
    iewgnaw
        6
    iewgnaw  
       2014-10-13 11:32:44 +08:00
    应该是数据库大小写不敏感,你直接用数据库命令查询试试看呢
    wuxianglong
        7
    wuxianglong  
       2014-10-13 16:13:25 +08:00
    数据库不支持大小写敏感
    larkifly
        8
    larkifly  
    OP
       2014-10-13 16:13:49 +08:00
    @iewgnaw
    @y10n
    @zeq
    数据库配置错误
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1253 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:21 · PVG 07:21 · LAX 16:21 · JFK 19:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.