django-filter的基本使用


django-filter 查詢

創建model和視圖

from django.db import models


# Create your models here.

class Student(models.Model):
    SEX_CHOICES = (
        (0, '女'),
        (1, '男')
    )
    name = models.CharField(max_length=10)
    sex = models.SmallIntegerField(choices=SEX_CHOICES)
    courses = models.ManyToManyField('Course')
    teacher = models.ForeignKey('Teacher', on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name


class Teacher(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name


class Course(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import ModelViewSet
from . import serializer
from . import models
from . import filter


class StudentView(ModelViewSet):
    queryset = models.Student.objects.all()
    serializer_class = serializer.StudentSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = filter.StudentFilter
from django_filters.rest_framework import FilterSet
import django_filters
from . import models


class StudentFilter(FilterSet):
    # 原始查詢 + lookup_expr查詢表達式
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    # choice查詢
    sex = django_filters.ChoiceFilter(choices=models.Student.SEX_CHOICES)
    # 自定義choice value查詢
    sex_display = django_filters.CharFilter(method='get_sex_display')

    # 跨表查詢
    teacher = django_filters.CharFilter(field_name='teacher__name')

    class Meta:
        model = models.Student
        fields = '__all__'

    def get_sex_display(self, queryset, name, value):
        # print(self.qs)
        item = {i[1]: i[0] for i in models.Student.SEX_CHOICES}
        sex_value = item.get(value, None)
        if sex_value is not None:
            condition = {'sex': sex_value}
            return queryset.filter(**condition)
        return queryset

定義filterset_fields

  • 在視圖類定義屬性filterset_fieldsfilterset_fields為一個列表或元祖,該字段中的元素為模型類對應的字段,然后在視圖的url里面即可get傳參查找
    -- 需要DjangoFilterBackend支持和django_filter支持

通用搜索

  • 在試圖類定義屬性search_fieldssearch_fields為一個列表或元祖,該字段中的元素為模型類對應的字段
  • 在url中使用關鍵字search中查找,即可找到所有search_fields匹配到的內容,關鍵字search字段可被定義的SEARCH_PARAM屬性覆蓋
    --需要SearchFilter支持
    --注意: search可支持擴表查詢如user__details__name,但是search_fields里面的內容最終指向的都應該是字符串類型

詳情:https://www.django-rest-framework.org/api-guide/filtering/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM