有没有一种方法可以仅在使用django-rest-framework指定时显示字段?

时间:2019-08-04 00:28:16

标签: django django-rest-framework

我正在使用django-rest-framework,https://www.django-rest-framework.org/api-guide/serializers/

只有在?field=X参数中指定了字段时,才可以显示该字段吗?如果我尝试这样做:

class TopLevelJobSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
    children_job_statuses = serializers.ReadOnlyField()

    class Meta:
        model = TopLevelJob # This inherits from Job, which has id, name
        fields = ('id', 'name')

我得到AssertionError: The field 'children_job_statuses' was declared on serializer TopLevelJobSerializer, but has not been included in the 'fields' option.

children_job_statuses是一个需要花费一些时间才能加载的属性。我只想通过调用/api/top_level_job/?fields=children_job_statuses

显式地调用它

我该怎么做?我需要一个全新的序列化器吗?

1 个答案:

答案 0 :(得分:0)

这对我有用:

def get_fields(self, *args, **kwargs):
    fields = super().get_fields(*args, **kwargs)
    request = self.context.get('request')
    if request is None or not 'fields' in request.query_params or 'children_job_statuses' not in \
            request.query_params['fields']:
        fields.pop('children_job_statuses', None)

    return fields