代码之家  ›  专栏  ›  技术社区  ›  Saelyth

如何在peewee中生成这个SQL查询

  •  2
  • Saelyth  · 技术社区  · 7 年前

    我正在从 sqlite3 peewee 到目前为止,它工作得很好,但是我不知道如何移植这个查询:

    query = ("SELECT * FROM things 
    WHERE Fecha substr(Fecha,7)||'/'||substr(Fecha,4,2)||'/'||substr(Fecha,1,2) 
    BETWEEN ? AND ?", my_field, my_second_field)
    

    在peewee我已经走了这么远:

    where_condition = database.fecha.fn.Substr(database.fecha, 7)
                     .concat('/')
                     .concat(database.fecha.fn.Substr(database.fecha, 4,2))
                     .concat('/')
                     .concat(database.fecha.fn.Substr(database.fecha, 1,2))
                     .between(my_field, my_second_field)
    database.select().where(where_condition)
    

    但它不起作用,我不知道如何连接peewee上的子字符串。

    >>> 'TextField' has no attribute 'fn'
    

    更新: 很重要的一点是,当条件是一个外部变量时,因为它只是多个过滤器中的一个。我用不同的方法制作不同的过滤器,然后把它们一起传递给 where 作为元组(我认为 fn 函数不能工作,因为它)。其完整代码为:

    for record in database.select().where(*self.build_where_conditions())
        # Do something
    
    def build_where_conditions(self):
        where_condition = []
        # first_thing
        if self.checkfirst_thing.isChecked():
           where_condition.append(database.first_thing == first_thing)
        # something
        if self.checksomething.isChecked():
            where_condition.append(database.something == something)
        # client
        if self.checkclient.isChecked():
            where_condition.append(database.client == client)
        # Serie
        if self.checkSerie.isChecked():
            where_condition.append(database.code.startswith("{0}{1}".format("18", serie)))
        # Code
        if self.checkCode.isChecked():
            where_condition.append(database.code.between(
                "{0}{1}".format("18", code1),
                "{0}{1}".format("18", code2)))
        # NOTE: Must always return a tuple
        if len(where_condition) >= 1:
            return where_condition
        return (None,)
    

    任何关于如何正确地做这件事的建议都是值得赞赏的。

    1 回复  |  直到 7 年前
        1
  •  1
  •   coleifer    7 年前

    “fn”应该是单独的。这不是一个属性(就像错误说的那样。

    from peewee import fn
    
    where_condition = fn.Substr(TheModel.the_text_field, 7)
                     .concat('/')
                     .concat(fn.Substr(TheModel.the_text_field, 4,2))
                     .concat('/') ... etc