在 python peewee 和 postgresql 的整数列上使用包含
use contains on a integer column with python peewee and postgresql
在我的 postgresql 数据库中有一个 table,它有一个整数数据类型的列。我想使用 peewee python orm 执行 .contains 操作。
它似乎不起作用,因为在进行比较之前需要将整数值转换为字符串。在 postgresql 中,您可以执行 value::text 然后整数值将是一个字符串,您可以在 like 表达式中使用它。
我可以使用 peewee orm 执行此操作,先转换值然后使用 .contains 吗?或者也许还有其他方法?
例如我想匹配 2022022 中的 20 个
谢谢
def python_partial_match(needle,key,haystack):
for item in haystack.select():
if needle in str(getattr(item,key,None)):
yield item
for result in python_partial_match("20","phone_number",UserModelClass):
print "GOT RESULT:",result
但我认为它对于大数据集来说真的很慢
或者我认为你可以做类似的事情
PostgresqlDatabase.register_ops({'::', '::'})
@Node.extend()
def cast(self, as_type):
return Expression(self, '::', SQL(as_type))
DataModel.select().where(DataModel.integer_col.cast('str').contains("20"))
也许......我没有测试那个演员......(见http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=cast#Node.extend)
实际上,在 postgres 的 playhouse 中似乎有一个内置的 cast
参见 http://docs.peewee-orm.com/en/latest/peewee/playhouse.html?highlight=cast#cast
我找到了另一种方法。我还在上面测试了 coleifer 的解决方案,效果很好。
我最终使用了 postgresql 格式化函数 https://www.postgresql.org/docs/9.3/static/functions-formatting.html
query.where(fn.TO_CHAR(Url.http_status_code, '999').contains(search_val))
我看到了几个答案,但我将添加我自己的 .02 作为库的开发者。
from playhouse.shortcuts import cast
query.where(cast(Url.http_status_code, 'text').contains(search_val))
我不确定哪个性能更好(可能 TO_CHAR),但以防万一您正在寻找更通用的东西,您可以使用 cast
.
在我的 postgresql 数据库中有一个 table,它有一个整数数据类型的列。我想使用 peewee python orm 执行 .contains 操作。
它似乎不起作用,因为在进行比较之前需要将整数值转换为字符串。在 postgresql 中,您可以执行 value::text 然后整数值将是一个字符串,您可以在 like 表达式中使用它。
我可以使用 peewee orm 执行此操作,先转换值然后使用 .contains 吗?或者也许还有其他方法?
例如我想匹配 2022022 中的 20 个
谢谢
def python_partial_match(needle,key,haystack):
for item in haystack.select():
if needle in str(getattr(item,key,None)):
yield item
for result in python_partial_match("20","phone_number",UserModelClass):
print "GOT RESULT:",result
但我认为它对于大数据集来说真的很慢
或者我认为你可以做类似的事情
PostgresqlDatabase.register_ops({'::', '::'})
@Node.extend()
def cast(self, as_type):
return Expression(self, '::', SQL(as_type))
DataModel.select().where(DataModel.integer_col.cast('str').contains("20"))
也许......我没有测试那个演员......(见http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=cast#Node.extend)
实际上,在 postgres 的 playhouse 中似乎有一个内置的 cast
参见 http://docs.peewee-orm.com/en/latest/peewee/playhouse.html?highlight=cast#cast
我找到了另一种方法。我还在上面测试了 coleifer 的解决方案,效果很好。 我最终使用了 postgresql 格式化函数 https://www.postgresql.org/docs/9.3/static/functions-formatting.html
query.where(fn.TO_CHAR(Url.http_status_code, '999').contains(search_val))
我看到了几个答案,但我将添加我自己的 .02 作为库的开发者。
from playhouse.shortcuts import cast
query.where(cast(Url.http_status_code, 'text').contains(search_val))
我不确定哪个性能更好(可能 TO_CHAR),但以防万一您正在寻找更通用的东西,您可以使用 cast
.