Django in / not in query

前端 未结 6 1778
不知归路
不知归路 2020-12-02 14:56

I\'m trying to figure out how to write a \'not in\' style query in django. For example, the query structure I\'m thinking of would look like this.

select tab         


        
6条回答
  •  执笔经年
    2020-12-02 15:26

    You can write a custom lookup for Django queries:

    From the documentation: "Let’s start with a simple custom lookup. We will write a custom lookup ne which works opposite to exact. Author.objects.filter(name__ne='Jack') will translate to the SQL: "author"."name" <> 'Jack'"

    from django.db.models import Lookup
    
    class NotEqual(Lookup):
        lookup_name = 'ne'
    
        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 <> %s' % (lhs, rhs), params
    

提交回复
热议问题