定义model
# models.py class Product(models.Model):
name = models.CharField(max_length=255)
author = models.CharField(max_length=255)
price = models.DecimalField()
description = models.TextField()
定义filter
# filters.py import django_filters class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='iexact') # iexact表示精确匹配, 并且忽略大小写
author = django_filters.CharFilter(lookup_expr='icontains') #icontains表示模糊查询(包含),并且忽略大小写
price = django_filters.NumberFilter(look_expr='exact') #exact表示精确匹配
desc = django_filters.CharFilter('description', lookup_expr='contains') #对'description'字段进行操作,不填默认为desc
#price__lte = django_filters.NumberFilter('price', lookup_expr='lte') #lte表示小于
#price__gte = django_filters.NumberFilter('price', look_expr='gte') # gte表示大于
class Meta:
model = Product
fields = ['name', 'author', 'price', 'description']
#fields = {
'price': ['lt', 'gt']
}
views中使用
class ProductViewSets(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (DjangoFilterBackend,)
filter_class = ProductFilter
search_fields = ('name', 'description') # 模糊搜索的字段
ordering_fields = ('price',) # 排序的字段