在Django模型QuerySets中,我看到有一个__gt和__lt用于比较值,但是否有__ne或!=(不等于)?我想用一个不等于来过滤掉。例如,对于
Model:
bool a;
int x;
我想做的
results = Model.objects.exclude(a=True, x!=5)
!=语法不正确。我也试过__ne。
我最终使用:
results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5)
有三种选择:
Chain exclude and filter
results = Model.objects.exclude(a=True).filter(x=5)
Use Q() objects and the ~ operator
from django.db.models import Q
object_list = QuerySet.filter(~Q(a=True), x=5)
Register a custom lookup function
from django.db.models import Lookup
from django.db.models import Field
@Field.register_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
Which can the be used as usual:
results = Model.objects.exclude(a=True, x__ne=5)