SyntaxError: keyword argument repeated
Asked Answered
C

2

8

I have the below queryset:

site_list = SiverifyVerificationSite.objects.filter(pattern_id=int(p_id), if_target=bundle.obj.pattern.if_target).exclude(ptrf__istartswith='ptrf-mt23run1-')

It works if I give one exclude filter whereas If I include the second filter in exclude it throws (SyntaxError: keyword argument repeated). Ideally what I want is:

site_list = SiverifyVerificationSite.objects.filter(pattern_id=int(p_id), if_target=bundle.obj.pattern.if_target).exclude(ptrf__istartswith='ptrf-mt23run1-', ptrf__istartswith='ptrf-20251-') 

Is there any operators to do this. Thanks.

Cita answered 17/3, 2017 at 4:3 Comment(0)
B
7

You may just chain the excludes:

qs = qs.exclude(ptrf__istartswith='ptrf-mt23run1-')
qs = qs.exclude(ptrf__istartswith='ptrf-20251-')

It does not cause any extra queries this way - Django won't evaluate the queryset until necessary.

An alternative is to build up the filter with Q objects.

from django.db.models import Q
q = Q(ptrf__istartswith='ptrf-mt23run1-') | Q(ptrf__istartswith='ptrf-20251-')
qs = qs.exclude(q)
Brisesoleil answered 17/3, 2017 at 4:6 Comment(2)
Chain will work. I was wondering if there might be any operators to do this.Cita
There is. Added an alternative option which uses | operator on Q objects. I think chaining is more readable, though.Brisesoleil
L
0

I got the same error below:

SyntaxError: keyword argument repeated: post__contains

When writing the filter() code with 2 post__contains arguments in test() view to run AND operator as shown below:

# "store/views.py"

from .models import Blog
from django.http import HttpResponse

def test(request):
    # Here
    qs = Blog.objects.filter(
             post__contains="popular", post__contains="simple"
         )      # ↑ ↑ ↑ Here ↑ ↑ ↑        # ↑ ↑ ↑ Here ↑ ↑ ↑
    print(qs)

    return HttpResponse("Test")

So, I used & or Q() and & to run AND operator with filter() as shown below:

# "store/views.py"

from .models import Blog
from django.db.models import Q
from django.http import HttpResponse

def test(request):

    # With "&"
                                                     # ↓ Here
    qs = Blog.objects.filter(post__contains="popular") & \
         Blog.objects.filter(post__contains="simple")
    print(qs)

    # With "Q()" and "&" 
                           # ↓ Here                    # ↓ Here
    qs = Blog.objects.filter(Q(post__contains="popular") & 
                             Q(post__contains="simple"))
    print(qs)              # ↑ Here

    return HttpResponse("Test")

Then, the error above was solved:

<QuerySet [<Blog: Python is popular and simple.>]> # With "&"
<QuerySet [<Blog: Python is popular and simple.>]> # With "Q()" and "&"
[22/Dec/2022 12:08:22] "GET /store/test/ HTTP/1.1" 200 9
Longways answered 22/12, 2022 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.