sql “LIKE” equivalent in django query

前端 未结 5 1250
星月不相逢
星月不相逢 2020-12-13 05:19

What is the equivalent of this SQL statement in django?

SELECT * FROM table_name WHERE string LIKE pattern;

How do I implement this in djan

5条回答
  •  -上瘾入骨i
    2020-12-13 05:44

    This can be done with Django's custom lookups. I have made the lookup into a Django-like-lookup application. After installing it the __like lookup with the % and _ wildcards will be enabled.

    All the necessary code in the application is:

    from django.db.models import Lookup
    from django.db.models.fields import Field
    
    
    @Field.register_lookup
    class Like(Lookup):
        lookup_name = 'like'
    
        def as_sql(self, compiler, connection):
            lhs, lhs_params = self.process_lhs(compiler, connection)
            rhs, rhs_params = self.process_rhs(compiler, connection)
            params = lhs_params + rhs_params
            return '%s LIKE %s' % (lhs, rhs), params
    

提交回复
热议问题