我正在使用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
我该怎么做?我需要一个全新的序列化器吗?
答案 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