manosim / manosim/django-rest-framework-docs

get_serializer_class doesn't recreate same conditions as would be used by DRF

Open
#168 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
641
Forks
178
PR merge metrics
No merged PRs in 30d

Description

Where `get_serializer_class()` is used to determine which serializer would be used for a `ModelViewSet`, it doesn't re-create the same environment as DRF would use when servicing an actual API request, and so it may return different results (and thus incorrect documentation).

As an example, I have the following method, which uses a cut-down serializer for list actions, and a full-content serializer for retrieve actions:

```python
class FooViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Foo.objects.all()

def get_serializer_class(self):
if hasattr(self, 'action'):
if self.action == 'list':
return FooListSerializer
elif self.action == 'retrieve':
return FooSerializer

return serializers.Default
```

drfdocs doesn't currently set the `self.action` member before calling `get_serializer_class()`, so it gets the default serializer with no fields, whereas an actual API request would get either the `FooSerializer` or the `FooListSerializer`.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from the get_serializer_class() call used during documentation generation and compare its setup with the ModelViewSet conditions described in the issue. Ensure the action context matches list and retrieve API requests, then verify that generated documentation uses FooListSerializer and FooSerializer rather than the default serializer.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
api, documentation
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.