在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)
如果我们需要基于我们可以使用的子查询集来排除/否定,
有条件的过滤器:
当条件表达式返回布尔值时,可以直接在过滤器中使用它。这里non_unique_account_type返回一个布尔值。但是,我们仍然可以在过滤器中使用它。
>>> non_unique_account_type = Client.objects.filter(
... account_type=OuterRef('account_type'),
... ).exclude(pk=OuterRef('pk')).values('pk')
>>> Client.objects.filter(~Exists(non_unique_account_type))
在SQL术语中,它的计算结果为:
SELECT * FROM client c0
WHERE NOT EXISTS (
SELECT c1.id
FROM client c1
WHERE c1.account_type = c0.account_type AND NOT c1.id = c0.id
)