django和django rest框架的Json数据过滤器
kfjsonfilter的Python项目详细描述
KF pubsub公司
使用django和django rest框架实现JsonFieldFilter和JsonFieldSearchFilter
安装
与要求.txt
在requirements.txt
文件中添加以下行:
kfjsonfilter
有PIP
^{pr2}$入门
实现了两个基本过滤器:JsonFieldFilter和JsonFieldSearchFilter。在
JsonFieldFilter
允许从json对象创建数据过滤器。有必要在django rest框架视图集中声明两个元素:json_字段和json_过滤器
TYPE | DESCRIPTION | |
---|---|---|
json_field | string | Indicates the json field object form the model |
json_filters | list of dicts | Indicates the field thats allow filter and lookup type for each type |
json_过滤器结构
允许按json数据中的任何值进行筛选。每个元素都必须包含在字典中,关键字为:field和lookup。在
json_filters = [{'field': <field_name>, 'lookup': <lookup>}, ...]
^{tb2}$
JsonFieldSearchFilter
允许从json对象创建数据筛选器和搜索筛选器。有必要在django rest框架视图集中声明三个元素:json_字段和search_字段
TYPE | DESCRIPTION | |
---|---|---|
json_field | string | Indicates the json field object form the model |
json_filters | list of dicts | Indicates the field thats allow filter by a field and lookup type for each type |
search_fields | list of dicts | Indicates the field thats allow search by a field and lookup type for each type |
json过滤器和搜索字段结构
允许按json数据中的任何值进行筛选/搜索。每个元素都必须包含在字典中,关键字为:field和lookup。在
json_filters = [{'field': <field_name>, 'lookup': <lookup>}, ...]
^{tb2}$
另外,当查找为“日期范围”时,字段名称必须以[]结尾
示例
Django模型
class MyModel(models.Model):
data = JSONField(default=dict)
For example:
data = {'creation_date': '2020-01-01', 'total': 3, 'name': 'Pedro Miguel'}
Django Rest框架视图
class MyModelViewSet(ListAPIView):
queryset = MyModel.objects.all()
filter_backends = [JsonFieldFilter, DjangoFilterBackend, OrderingFilter]
json_field = 'data'
json_filters = [{'field': 'creation_date', 'lookup': 'date_range'}, {'field': 'total', 'lookup': 'gte'}]
or
class MyModelViewSet(ListAPIView):
queryset = MyModel.objects.all()
filter_backends = [JsonFieldSearchFilter, DjangoFilterBackend, OrderingFilter]
json_field = 'data'
json_filters = [{'field': 'creation_date', 'lookup': 'lte'}, {'field': 'total', 'lookup': 'gte'}]
search_fields = [{'field': 'name', 'lookup': 'icontains'}]
- 项目
标签: