Skip to content

Commit 2e3e89c

Browse files
browniebrokeintgr
andauthored
Add FAQ section to README to explain generics with ModelSerializer (#444)
Co-authored-by: Marti Raudsepp <[email protected]>
1 parent 9bce985 commit 2e3e89c

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,20 @@ plugins =
2626

2727
in your `mypy.ini` file.
2828

29+
## FAQ
30+
31+
### Model instance is inferred as `Any` instead of my `Model` class
32+
33+
When subclassing `ModelSerializer`, add a [type argument](https://peps.python.org/pep-0484/#generics) to type-hint the related model class, for example:
34+
35+
```python
36+
class MyModelSerializer(serializers.ModelSerializer[MyModel]):
37+
class Meta:
38+
model = MyModel
39+
fields = ("id", "example")
40+
```
41+
42+
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]`.
2943

3044
## To get help
3145

0 commit comments

Comments
 (0)