Django反向包含/ icontains [英] Django reverse to contains/icontains
问题描述
在此问题已解决问题, code> LIKE 在SQL中操作,例如,如果字段名称是Peter Johnson,我们可以通过这样的查询找到它:
In this question was solved problem for reverse LIKE
operation in SQL, for example if field name is "Peter Johnson", we could find it by such query:
select name from user where "Mr. Peter Johnson" like CONCAT('%', name, '%')
有没有办法在Django中做这样的事情 Q
object(我正在构建一个大的查询,所以使用raw SQL查询不合理)?
Is there any way to do such thing in Django Q
object (I'm building a big query, so using raw SQL query will not be rational)?
推荐答案
不幸的是,Django的ORM没有内置反向LIKE的东西。但是, .extra()
子句可能会比原始查询更容易。
Unfortunately, Django's ORM doesn't have anything built-in for reverse LIKEs. But an .extra()
clause may make it a bit easier than a raw query.
我使用了这个:
qs.extra(
where=['''%s LIKE %s.%s'''],
params=(
"string to match",
FooModel._meta.db_table,
"bar_field",
),
)
上述代码的问题是
1)它不适用于此表单中的sqlite后端(附近的语法错误),它可以在查询中硬编码的表/列名称使用,这并不总是安全的丑陋);
1) it doesn't work with sqlite backend in this form ("syntax error near .", it does work with table/column names hardcoded in query... which is not always safe and always ugly);
和2)它需要FooModel.bar_field以类似样式%的数据%,所以你可以不匹配任意字符串(可以使用
%s LIKE CONCAT(%,%s。%s,%)
使它成为DBMS特定的,这不是很好)。
and 2) it requires FooModel.bar_field to have data %in like style%
so you can't match arbitrary strings (this can be fixed with a query like %s LIKE CONCAT("%", %s.%s, "%")
but it'll make it DBMS-specific, which is not good).
反转LIKE本身应该可以与任何ma jor DBMS,但是我只测试了sqlite和postgres。
Reversed LIKE itself should probably work with any major DBMS, but I tested it only on sqlite and postgres.
也许有人应该泛化我的解决方案,并创建一个可重用的,与DBMS无关的应用程序与特殊的子类查询器/管理器/这个具体任务的Q对象...
Maybe someone should generalize my solution and create a reusable, DBMS-agnostic app with special subclassed queryset/manager/Q-object for this specific task...
这篇关于Django反向包含/ icontains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!