Django custom for complex Func (sql function)

前端 未结 3 1836
你的背包
你的背包 2021-01-04 04:54

In the process of finding a solution for Django ORM order by exact, I created a custom django Func:

from django.db.models import Func

class Position(Func):
         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 05:34

    basis on the John Moutafis ideas, final function is (inside the __init__ method we use Values for safety result.)

    from django.db.models import Func, F, Value
    from django.db.models.functions import Lower
    
    
    class Instr(Func):
        function = 'INSTR'
    
        def __init__(self, string, substring, insensitive=False, **extra):
            if not substring:
                raise ValueError('Empty substring not allowed')
            if not insensitive:
                expressions = F(string), Value(substring)
            else:
                expressions = Lower(string), Lower(Value(substring))
            super(Instr, self).__init__(*expressions)
    
        def as_postgresql(self, compiler, connection):
            return self.as_sql(compiler, connection, function='STRPOS')
    

提交回复
热议问题