From 2e3e89c431c17be4aa0ec69e1b55f9a3ddc3b702 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Wed, 4 Oct 2023 21:21:06 +0100 Subject: [PATCH] Add FAQ section to README to explain generics with ModelSerializer (#444) Co-authored-by: Marti Raudsepp --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 1061d6ff6..85c6df163 100644 --- a/README.md +++ b/README.md @@ -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