有没有办法在 Django 中进行不区分大小写的 IN 查询?
Django 中几乎每种查找都有一个不区分大小写的版本,除了 in,它出现了。
这是一个问题,因为有时我需要进行查找,确定情况会不正确。
Products.objects.filter(code__in=[user_entered_data_as_list])
我能做些什么来解决这个问题吗?人们是否想出了解决这个问题的方法?
Nearly every kind of lookup in Django has a case-insensitive version, EXCEPT in, it appears.
This is a problem because sometimes I need to do a lookup where I am certain the case will be incorrect.
Products.objects.filter(code__in=[user_entered_data_as_list])
Is there anything I can do to deal with this? Have people come up with a hack to work around this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我通过使 MySQL 数据库本身不区分大小写来解决这个问题。我怀疑 Django 的人是否有兴趣将其添加为一项功能或提供有关如何提供自己的字段查找的文档(假设甚至可以在不为每个数据库后端提供代码的情况下实现),
诚然,这是一种方法它很笨重。
I worked around this by making the MySQL database itself case-insensitive. I doubt that the people at Django are interested in adding this as a feature or in providing docs on how to provide your own field lookup (assuming that is even possible without providing code for each db backend)
Here is one way to do it, admittedly it is clunky.
如果您的数据库是 MySQL,Django 会不区分大小写地处理 IN 查询。虽然我不确定其他
编辑1:
将给出以下结果,其中城市名称是
If your database is MySQL, Django treats IN queries case insensitively. Though I am not sure about others
Edit 1:
will give following result in which city name is
您可以注释降低的代码并降低输入的数据
You can do it annotating the lowered code and also lowering the entered data
如果不会产生冲突,可能的解决方法是在保存对象时和在
过滤器
中将字符串转换为大写或小写。If it won't create conflicts, a possible workaround may be transforming the strings to upper or lowercase both when the object is saved and in the
filter
.这是一个不需要案例准备的 DB 值的解决方案。
它还在数据库引擎端进行过滤,这意味着比迭代
objects.all()
具有更高的性能。另一个有效的解决方案是使用 extra 和相当可移植的原始 SQL
lower()
函数:Here is a solution that do not require case-prepared DB values.
Also it makes a filtering on DB-engine side, meaning much more performance than iterating over
objects.all()
.The other efficient solution is to use extra with quite portable raw-SQL
lower()
function:另一个解决方案 - 尽管很粗糙 - 是将原始字符串的不同情况包含在“in”过滤器的列表参数中。例如:使用 ['a', 'b', 'c', 'A', 'B', 'C'] 代替 ['a', 'b', 'c']。
这是一个从字符串列表构建此类列表的函数:
Another solution - albeit crude - is to include the different cases of the original strings in the list argument to the 'in' filter. For example: instead of ['a', 'b', 'c'], use ['a', 'b', 'c', 'A', 'B', 'C'] instead.
Here's a function that builds such a list from a list of strings:
使用
Q 进行查找
对象 可以构建为仅访问数据库一次:A lookup using
Q
object can be built to hit the database only once:更优雅一点的方式是这样的:
A litle more elegant way would be this: