Django rest框架groupby归档并序列化为json

时间:2019-05-28 04:24:33

标签: python django-models django-rest-framework

我想根据URL中发送的查询参数对数据进行分组。我正在使用djanogo rest框架来实现REST API。例子

如果以下网址已发送到服务器

http://example.com/query?groupby=age

然后我要根据年龄字段将所有人分组,就像下面的数据示例

  [
  {
    "groupby": 20,
    "person": "Jhon",
    "email": "n@g.com",
    "phone": "100",
    "companies": [
      {
        "company1": "address1"
      },
      {
        "company1": "address2"
      }
    ]
  },
  {
    "groupby": 30,
    "person": "Jhon",
    "email": "n@g.com",
    "phone": "100",
    "companies": [
      {
        "company1": "address1"
      },
      {
        "company1": "address2"
      }
    ]
  }
]

我的模型和视图集如下所示

 class ListFilter(Filter):
      def filter(self, qs, value):
        value_list = value.split(u',')
        return super(ListFilter, self).filter(qs, Lookup(value_list, 'in'))

class SqureFeetFilter(Filter):
    def filter(self, qs, value):
        value_list = value.split(u',')
        return super(SqureFeetFilter, self).filter(qs, Lookup(value_list, 'range'))

class ProfileFiltter(django_filters.FilterSet):
    person = ListFilter(name='person')
    sf = SqureFeetFilter(name='age',lookup_expr='range')

    class Meta:
        model = Profile
        fields =  [ 'person','age','email','phone','companies']

class ProfileSearchVieset(viewsets.ModelViewSet):
        queryset = Profile.objects.all()
        serializer_class = ProfileSerializer
        permission_classes = [IsAuthenticated]
        filter_backends = (DjangoFilterBackend,)
        filter_class =ProfileFiltter

请指导我如何根据查询参数对数据进行分组并将其序列化为json格式。

0 个答案:

没有答案