Django过滤器,如何使多个字段搜索?(使用django-filter!) [英] Django-filter, how to make multiple fields search? (with django-filter!)

查看:48
本文介绍了Django过滤器,如何使多个字段搜索?(使用django-filter!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Django过滤器从以下模型中搜索多个字段:

How can I make multiple fields search with Django-filter from model like:

class Location(models.Model):
    loc = models.CharField(max_length=100, blank=True)
    loc_mansioned = models.CharField(max_length=100, blank=True)
    loc_country = models.CharField(max_length=100, blank=True)
    loc_modern = models.CharField(max_length=100, blank=True)

我的网站上需要一个输入字段,可以在位置模型的所有字段中进行搜索

I need one input field on my website, that can search over all fields of Location model

推荐答案

您可能可以创建一个自定义过滤器,并执行以下操作:

You can probably create a custom filter and do something like this:

from django.db.models import Q
import django_filters


class LocationFilter(django_filters.FilterSet):
    q = django_filters.CharFilter(method='my_custom_filter')

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

    def my_custom_filter(self, queryset, name, value):
        return Location.objects.filter(
            Q(loc__icontains=value) | Q(loc_mansioned__icontains=value) | Q(loc_country__icontains=value) | Q(loc_modern__icontains=value)
        )

这将按那些字段中的任何一个进行过滤.您可以将 contains 替换为所需的任何内容.

This would filter by any of of those fields. You can replace the icontains with whatever you want.

这篇关于Django过滤器,如何使多个字段搜索?(使用django-filter!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆