Programing

장고 쿼리 셋 필터링에서 같지 않음을 어떻게합니까?

lottogame 2020. 10. 3. 09:46
반응형

장고 쿼리 셋 필터링에서 같지 않음을 어떻게합니까?


장고 모델 검색어 세트, 나는 거기 것을 볼 __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)

어쩌면 Q 객체는 이 문제에 대한 도움이 될 수 있습니다. 나는 그것들을 사용한 적이 없지만 일반 파이썬 표현처럼 부정하고 결합 될 수있는 것 같습니다.

업데이트 : 방금 사용해 보았지만 꽤 잘 작동하는 것 같습니다.

>>> from myapp.models import Entry
>>> from django.db.models import Q

>>> Entry.objects.filter(~Q(id = 3))

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

귀하의 쿼리에 이중 음수가있는 것 같습니다. x가 5가 아닌 모든 행을 제외하려고합니다. 즉, x가 5 인 모든 행을 포함하려고합니다.이 방법이 효과가있을 것이라고 생각합니다.

results = Model.objects.filter(x=5).exclude(a=true)

특정 질문에 답하기 위해 "같지 않음"은 없지만 장고는 "필터"와 "제외"메소드를 모두 사용할 수 있기 때문에 원하는 결과를 얻기 위해 항상 논리 라운드를 전환 할 수 있기 때문일 것입니다.


field=value쿼리 구문은 field__exact=value. 즉, Django는 식별자의 쿼리 필드에 쿼리 연산자를 넣습니다 . Django는 다음 연산자를 지원합니다.

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
year
month
day
week_day
isnull
search
regex
iregex

Dave Vogt가 제안 하고 사용 filter()하거나 Jason Baker가 제안한exclude() 것처럼 Q 개체와 결합 하여 가능한 모든 쿼리에 필요한 것을 정확하게 얻을 수 있다고 확신 합니다.


It's easy to create a custom lookup with Django 1.7. There's an __ne lookup example in Django official documentation.

You need to create the lookup itself first:

from django.db.models import Lookup

class NotEqual(Lookup):
    lookup_name = 'ne'

    def as_sql(self, qn, connection):
        lhs, lhs_params = self.process_lhs(qn, connection)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params
        return '%s <> %s' % (lhs, rhs), params

Then you need to register it:

from django.db.models.fields import Field
Field.register_lookup(NotEqual)

And now you can use the __ne lookup in your queries like this:

results = Model.objects.exclude(a=True, x__ne=5)

In Django 1.9/1.10 there are three options.

  1. Chain exclude and filter

    results = Model.objects.exclude(a=true).filter(x=5)
    
  2. Use Q() objects and the ~ operator

    from django.db.models import Q
    object_list = QuerySet.filter(~Q(a=True), x=5)
    
  3. Register a custom lookup function

    from django.db.models import Lookup
    from django.db.models.fields 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
    

    The register_lookup decorator was added in Django 1.8 and enables custom lookup as usual:

    results = Model.objects.exclude(a=True, x__ne=5)
    

While with the Models, you can filter with =, __gt, __gte, __lt, __lte, you cannot use ne, != or <>. However, you can achieve better filtering on using the Q object.

You can avoid chaining QuerySet.filter() and QuerySet.exlude(), and use this:

from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')

Pending design decision. Meanwhile, use exclude()

The Django issue tracker has the remarkable entry #5763, titled "Queryset doesn't have a "not equal" filter operator". It is remarkable because (as of April 2016) it was "opened 9 years ago" (in the Django stone age), "closed 4 years ago", and "last changed 5 months ago".

Read through the discussion, it is interesting. Basically, some people argue __ne should be added while others say exclude() is clearer and hence __ne should not be added.

(I agree with the former, because the latter argument is roughly equivalent to saying Python should not have != because it has == and not already...)


You should use filter and exclude like this

results = Model.objects.exclude(a=true).filter(x=5)

Using exclude and filter

results = Model.objects.filter(x=5).exclude(a=true)

The last bit of code will exclude all objects where x!=5 and a is True. Try this:

results = Model.objects.filter(a=False, x=5)

Remember, the = sign in the above line is assigning False to the parameter a and the number 5 to the parameter x. It's not checking for equality. Thus, there isn't really any way to use the != symbol in a query call.


당신이 찾고있는 무슨 중 하나가 모든 객체 a=false 또는 x=5 . Django에서 쿼리 셋 간의 연산자 |역할을합니다 OR.

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

결과 = Model.objects.filter (a = True) .exclude (x = 5)
이 SQL을 생성합니다.
! = 0 및 x! = 5 인 tablex에서 *를 선택하십시오.
SQL은 True / False 필드가 표시되는 방식과 데이터베이스 엔진에 따라 다릅니다. 장고 코드 만 있으면됩니다.


Django-model-values (disclosure : author)는 이 답변 에서와 같이 NotEqual 조회 의 구현을 제공합니다 . 또한 이에 대한 구문 지원을 제공합니다.

from model_values import F
Model.objects.exclude(F.x != 5, a=True)

이 질문에 대한 많은 오답을 조심하십시오!

Gerard의 논리는 정확하지만 쿼리 세트가 아닌 목록을 반환합니다 (중요하지 않을 수도 있음).

쿼리 셋이 필요한 경우 Q :

from django.db.models import Q
results = Model.objects.filter(Q(a=false) | Q(x=5))

This will give your desired result.

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) and ~Q(x=5))

for not equal you can use ~ on an equal query. obviously, Q can be used to reach the equal query.

참고URL : https://stackoverflow.com/questions/687295/how-do-i-do-a-not-equal-in-django-queryset-filtering

반응형