【问题标题】:use contains on a integer column with python peewee and postgresql在带有 python peewee 和 postgresql 的整数列上使用 contains
【发布时间】:2016-11-30 21:08:21
【问题描述】:

在我的 postgresql 数据库中有一个表,其中包含一个整数数据类型的列。我想使用 peewee python orm 执行 .contains 操作。

它似乎不起作用,因为在进行比较之前需要将整数值转换为字符串。在 postgresql 你可以做 value::text 然后整数值将是一个字符串,你可以在类似的表达式中使用它。

我可以使用 peewee orm 执行此操作,先转换值然后使用 .contains 吗?或者也许还有其他方法?

例如,我想匹配 2022022 中的 20 个

谢谢

【问题讨论】:

    标签: python sql postgresql peewee


    【解决方案1】:

    我看到了几个答案,但我将添加我自己的 .02 作为库的开发人员。

    from playhouse.shortcuts import cast
    
    query.where(cast(Url.http_status_code, 'text').contains(search_val))
    

    我不确定哪个性能更高(可能是 TO_CHAR),但如果您正在寻找更通用的东西,您可以使用 cast

    【讨论】:

      【解决方案2】:
      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

      实际上,在 playhouse 中似乎有一个内置的 cast 用于 postgres 参见 http://docs.peewee-orm.com/en/latest/peewee/playhouse.html?highlight=cast#cast

      【讨论】:

      • 不幸的是,这些建议对我不起作用,但我确实找到了方法
      【解决方案3】:

      我找到了另一种方法。我还在上面测试了 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))
      

      【讨论】:

        猜你喜欢
        • 2011-06-18
        • 2022-10-08
        • 2021-01-07
        • 2017-01-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多