django-filter用法

一. 环境准备

pip install Django==2.2 -i https://pypi.douban.com/simple
pip install djangorestframework==3.10 -i https://pypi.douban.com/simple
pip install django-filter==2.3.0 -i https://pypi.douban.com/simple

在Django的项目配置文件中安装并配置django_filters应用

INSTALLED_APPS = [
    ...
    'django_filters',
]

REST_FRAMEWORK = {
   # 过滤器默认后端
    'DEFAULT_FILTER_BACKENDS': (
           'django_filters.rest_framework.DjangoFilterBackend',),
}

二. 基本用法

1. models.py
class DomainName(models.Model):
    id = models.CharField(max_length=30, primary_key="true")
    name = models.CharField(max_length=50, null=False)
    email = models.CharField(max_length=50, null=False, default="")
2. serializers.py
from rest_framework import serializers
from .models import DomainName

class DomainSerializer(serializers.ModelSerializer):
  class Meta:
    model = DomainName
    fields = "__all__"
3.filters.py
from django_filters import rest_framework as filters
from .models import DomainName

class DomainFilter(filters.FilterSet):
    class Meta:
        model = DomainName
        fields = ['name']
4.views.py
from rest_framework.viewsets import ModelViewSet
from .models import DomainName
from .serializers import DomainSerializer
from .filters import DomainFilter

class DomainViewSet(ModelViewSet):
  queryset = DomainName.objects.all()
  serializer_class = DomainSerializer
  filter_class = DomainFilter
5.urls.py
from rest_framework.routers import DefaultRouter
from .views import DomainViewSet, domain_list
from django.urls import path

#SimpleRouter或者DefaultRouter创建的URL将附加尾部斜杠,参数trailing_slash=False可以取消尾部斜杠
router = DefaultRouter()

router.register('domaininfo', DomainViewSet, basename='domainList')

urlpatterns=[]+router.urls

然后就可以使用http://127.0.0.1:8000/aliyun/domaininfo/?name=iwos.com.cn来访问对应域名的详情。

其中aliyun是app的名字,这里没写项目中注册的URL

其他用法可以参考
https://zhuanlan.zhihu.com/p/110060840
https://blog.csdn.net/u014783334/article/details/124898763
https://blog.csdn.net/weixin_42143550/article/details/88124710

posted @ 2023-03-15 15:33  坚强的小蚂蚁  阅读(201)  评论(0编辑  收藏  举报