如何在Django中添加多个”OR”查询

huangapple go评论75阅读模式
英文:

How to add multiple "OR" queries in Django

问题

我有2个模型,ItemCategoryItem 模型有一个作为外键的 category 字段。

在我的 views.py 文件中,我从一个 POST 请求中获取了一组查询,queries = ['category1', 'category2', 'category3', ...]

我不知道我会从请求中获取多少个查询,我想要根据 category 字段过滤 Item 模型。

我尝试过以下方法:

from django.db.models import Q
from .models import Item, Category
from django import views

class myView(views.View):
    def post(self, request):
        queries = request.POST.get('queries', '')
        if queries:
            queriesList = []
            queries = queries.split(',')  # queries = ['category1', 'category2', ....]
            for query in queries:
                queriesList.append(Q(category__icontains=query))
            queryset = Item.objects.filter(*queriesList) # 这将使用 AND,但不会使用 OR
            # 我尝试过:queryset = Item.objects.filter([q | Q() for q in queriesList]) 但它不起作用

也尝试过 `queryset = Item.objects.filter(category__in=queries)`,但它区分大小写
英文:

I have 2 models, Item and Category, the model Item has category field as a foreign key

In my views.py I get a list of queries from a POST request queries = ['category1', 'category2', 'category3', ...]

I don't know the number of the queries I will get from the request, and I want to filter the Item model based on category field

I tried this

from django.db.models import Q
from .models import Item, Category
from django import views

class myView(views.View):
    def post(self, request):
        queries = request.POST.get('queries', '')
        if queries:
            queriesList = []
            queries = queries.split(',')  # queries = ['category1', 'category2', ....]
            for query in queries:
                queriesList.append(Q(category__icontains=query))
            queryset = Item.objects.filter(*queriesList) # this will do AND but won't do OR
            # I tried: queryset = Item.objects.filter([q | Q() for q in queriesList]) but it didn't work

Also I tried queryset = Item.objects.filter(category__in=queries)
but it's case sensitive

答案1

得分: 3

你可以使用 Q.OR 作为 _connector

from django.db.models import Q
from django import views
from .models import Category, Item

class myView(views.View):
    def post(self, request):
        queries = request.POST.get('queries', '')
        if queries:
            queryset = Item.objects.filter(
                *[Q(category__icontains=query) for query in queries.split(',')],
                _connector=Q.OR
            )

搜索通常通过GET请求完成,因此搜索查询出现在URL中,可以复制、收藏等,其中包括搜索查询。

英文:

You can use Q.OR as _connector:
<pre><code>from django.db.models import Q

from django import views

from .models import Category, Item

class myView(views.View):
def post(self, request):
queries = request.POST.get('queries', '')
if queries:
queryset = Item.objects.filter(
*[Q(category__icontains=query) for query in queries.split(',')],
<b>_connector=Q.OR</b>
)</code></pre>

searching is however normally done through a GET request, such that the search query appears in the URL, and thus the URL can be copied, bookmarked, etc. with the search query included.

答案2

得分: 1

q = Q()

for category in ['category1', 'category2', 'category3', ...]:
    q |= Q(category__icontains=category)

items = Item.objects.filter(q)

如果Item.category是外键,也许您想要使用类似category__name__icontains=category的东西。

英文:
q = Q()

for category in [&#39;category1&#39;, &#39;category2&#39;, &#39;category3&#39;, ...]:
    q |= Q(category__icontains=category)

items = Item.objects.filter(q)

If Item.category is a foreign key, maybe you want to use something like category__name__icontains=category.

huangapple
  • 本文由 发表于 2023年6月29日 02:19:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定