如何在不使用“SyntaxError:”的情况下使用“filter()”运行“AND”运算符关键字参数重复:“Django中的错误?

af7jpaap  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(122)

我有**Blog模型如下。* 我使用Django 3.2.16PostgreSQL**:

# "store/models.py"

from django.db import models

class Blog(models.Model):
    post = models.TextField()
    
    def __str__(self):
        return self.post

那么,store_blog在下面有2行

store_blog表格:

| 身份证|柱|
| - ------| - ------|
| * * 一个**| * * Python很流行而且简单。|
| * * 二
| * * Java既流行又复杂。|
然后,当在
test()视图中编写filter()代码**(带有2个post__contains参数)时,运行**AND运算符**,如下所示:

# "store/views.py"

from .models import Blog
from django.http import HttpResponse

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

    return HttpResponse("Test")

我得到了下面的错误:
语法错误:关键字参数重复:帖子包含
那么,如何在Django中使用**filter()运行AND运算符而不出现SyntaxError: keyword argument repeated:错误**呢?

iezvtpos

iezvtpos1#

可以使用**&或使用Q()&运行AND运算符**,如下所示:

# "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")

然后,您可以得到下面的结果:

<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

并且,根据PostgreSQL的查询日志,有**AND运算符**,如下所示,您可以选中在PostgreSQL上,如何记录带有事务查询(如"BEGIN"和"COMMIT")的查询

此外,您还可以使用**filter()|或使用Q()|运行OR运算符**,如下所示:

# "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")

然后,您可以得到下面的结果:

<QuerySet [<Blog: Python is popular and simple.>, <Blog: Java is popular and complex.>]>
<QuerySet [<Blog: Python is popular and simple.>, <Blog: Java is popular and complex.>]>
[22/Dec/2022 12:56:41] "GET /store/call_test/ HTTP/1.1" 200 9

其中,根据PostgreSQL的查询日志,有**OR操作符**,如下所示:

  • 请注意,您不应使用**andor来运行ANDOR运算符**,因为根据此答案,它们无法正常工作,实际上,只有**&的示例|* * 所以你应该像我上面展示的那样使用**&|**。

相关问题