DRF序列化程序:在StringRelatedField上排序

时间:2017-11-01 07:57:54

标签: django-rest-framework

我有ModelSerializer,其中包含来自链接模型的字段,如下所示。

owner_login = StringRelatedField(source='resource.owner.login_id', read_only=True)

我想在这个字段上添加动态排序,我该怎么做?

查看

class ProfileApplicationLogs(generics.ListCreateAPIView):
    model = ResourceLog
    serializer_class = ProfileApplicationLogSerializer
    ordering_fields = ('run_remediate', )
    ordering = ('-run_remediate',)

    def get_queryset(self):
        id = self.kwargs['userid']
        days = self.kwargs['days']
        now = datetime.datetime.now(timezone.utc)

        return ResourceLog.objects
                          .filter(Q(actual_start_time__isnull = True) |
                                  Q(actual_start_time__gt=earlier))\
                          .extra(tables=["cpe_resource_mgmt"],
                                 where=["resource_mgmt_id = cpe_resource_mgmt.id",
                                        "cpe_resource_mgmt.owner_id IN ( \
                                         select id from cpe_user \
                                         where is_active='Y' \
                                         connect by prior id = parent_id start with id = % s)"], params=[id])\ 
                                # .order_by('-actual_end_time')  // earlier I was doing this.

1 个答案:

答案 0 :(得分:1)

您的StringRelatedField只是一种表现形式。您需要在视图中下订单:

class YourListView(generics.ListAPIView):
    queryset = YourModel.objects.all()
    serializer_class = YourSerializer
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('resource__owner__login_id', )
    ordering = ('resource__owner__login_id',)  # add this only if you want to use it as default ordering

如果您未将其设为默认排序,那么您的请求应包含ordering这样的查询参数

http://example.com/api/yourmodel?ordering=resource__owner__login_id