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

e37o9pze  于 2023-07-01  发布在  Go
关注(0)|答案(2)|浏览(132)

我有2个模型,ItemCategory,模型Item具有类别字段作为外键
在我的views.py中,我从POST请求queries = ['category1', 'category2', 'category3', ...]中获得一个查询列表
我不知道我将从请求中获得的查询数量,我想根据类别字段过滤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) # 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

我也尝试了queryset = Item.objects.filter(category__in=queries),但它的大小写敏感

wqsoz72f

wqsoz72f1#

您可以将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中,并且因此URL可以被复制、加书签等。其中包括搜索查询。

rekjcdws

rekjcdws2#

q = Q()

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

items = Item.objects.filter(q)

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

相关问题