使用Django过滤器搜索所有内容

时间:2019-07-18 02:36:38

标签: django django-filter

我正在尝试搜索多个字段和全文警告表。我使用Django过滤器进行搜索,但没有返回结果。我还使用django过滤器引用了一些代码,并遵循它们,但是什么也没有。我该如何解决? 这是一些代码。

filters.py

import django_filters
from .models import Warnings


class WarningFilter(django_filters.FilterSet):
    title = django_filters.CharFilter(lookup_expr='icontains')
    detail = django_filters.CharFilter(lookup_expr='icontains')
    type = django_filters.CharFilter(lookup_expr='icontains')
    website = django_filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Warnings
        fields = ['title', 'detail', 'type', 'website']

views.py

def search(request):
    if request.method == 'GET':
        query = request.GET.get('q')
        result = WarningFilter(query, queryset=Warnings.objects.all())
    context = {'filters': result.qs}
    return render(request, 'pages/history_warning.html', context)

models.py

from django.db import models
from django.contrib.auth.models import User
import uuid


class Website(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    uri = models.CharField(max_length=200)
    def __str__(self):
        return self.name

class Warnings(models.Model):

    TYPE_WARNINGS = (
        ('security', "Cảnh báo bảo mật"),
        ('service', "Cảnh báo dịch vụ")
    )
    title = models.CharField(blank=True, null=True, max_length=255)
    detail = models.TextField(blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    type = models.CharField(choices=TYPE_WARNINGS, blank=True, null=True, max_length=255)
    website = models.ForeignKey(Website, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:0)

可能您可以使用filter.method来做到这一点:

class WarningFilter(django_filters.FilterSet):
    q = django_filters.CharFilter(method='filter_q')

    def filter_q(self, qs, name, value):
        return qs.filter(
            Q(title__icontains=value) | Q(detail__icontains=value) | Q(type__icontains=value) | Q(website__name__icontains=value)
        )

用法:

if request.method == 'GET':
    result = WarningFilter(request.GET, queryset=Warnings.objects.all())
    context = {'filters': result.qs}
    return render(request, 'pages/history_warning.html', context)