gpt4 book ai didi

Django - 如何在自定义过滤器中将 "or"条件添加到 queryset.filter

转载 作者:行者123 更新时间:2023-12-05 02:30:39 25 4
gpt4 key购买 nike

我想制作一个搜索过滤器,它只使用一个搜索字段在多个条件下的多个字段中进行搜索。我有这个 filters.py 文件:

import django_filters
from .models import Product


class ProductFilter(django_filters.FilterSet):
q = django_filters.CharFilter(method='search_filter', label='Cerca')

class Meta:
model = Product
fields = ['q']

def search_filter(self, queryset, name, value):
return queryset.filter(name__icontains=value, sku__iexact=value)

return queryset.filter(name__icontains=value, sku__iexact=value) 不起作用,return queryset.filter(Product(name__icontains=value) | Product(sku__iexact=value) ))我该怎么做?

最佳答案

您可以使用 Q objects [Django-doc] 进行过滤:

import django_filters
from django.db.models import Q
from .models import Product

class ProductFilter(django_filters.FilterSet):
q = django_filters.CharFilter(method='search_filter', label='Cerca')

class Meta:
model = Product
fields = ['q']

def search_filter(self, queryset, name, value):
return queryset.filter(<strong>Q(</strong>name__icontains=value<strong>) | Q(</strong>sku__iexact=value<strong>)</strong>)

关于Django - 如何在自定义过滤器中将 "or"条件添加到 queryset.filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71798874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com