Skip to content

Commit

Permalink
Add FAQ section to README to explain generics with ModelSerializer (#444
Browse files Browse the repository at this point in the history
)

Co-authored-by: Marti Raudsepp <[email protected]>
  • Loading branch information
browniebroke and intgr authored Oct 4, 2023
1 parent 9bce985 commit 2e3e89c
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ plugins =

in your `mypy.ini` file.

## FAQ

### Model instance is inferred as `Any` instead of my `Model` class

When subclassing `ModelSerializer`, add a [type argument](https://peps.python.org/pep-0484/#generics) to type-hint the related model class, for example:

```python
class MyModelSerializer(serializers.ModelSerializer[MyModel]):
class Meta:
model = MyModel
fields = ("id", "example")
```

Which means that methods where the model is being passed around will know the actual type of the model instead of being `Any`. The `instance` attribute on the above serializer will be `Union[MyModel, typing.Sequence[MyModel], None]`.

## To get help

Expand Down

0 comments on commit 2e3e89c

Please sign in to comment.