typeddjango / djangorestframework-stubs

PEP-484 stubs for django-rest-framework
MIT License
453 stars 117 forks source link

Subclassing generic serializer #669

Open H4rryK4ne opened 2 months ago

H4rryK4ne commented 2 months ago

I am getting mypy errors I do no completely understand. I have a generic base class and want to create a (generic) base serializer which shall be used by the specific serializer.

My code looks like this:

from typing import Generic, TypeVar
from django.db.models import Model
from rest_framework import serializers

class BaseClass(Model):
    class Meta:
        abstract = True

    @classmethod
    def some_base_class_method(cls) -> None:
        pass

class MyClass(BaseClass):
    class Meta:
        abstract = False

_M = TypeVar("_M", bound=BaseClass)

class BaseClassSerializer(serializers.ModelSerializer[_M]):
    def some_method(self) -> None:
        self.Meta.model.some_base_class_method()

class MyClassSerializer(BaseClassSerializer[MyClass]):
    class Meta:
        model = MyClass

Mypy errors:

error: "type[_MT?]" has no attribute "some_base_class_method"  [attr-defined]
            self.Meta.model.some_base_class_method()
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If I add BaseClassSerializer.Meta.model like this:

class BaseClassSerializer(serializers.ModelSerializer[_M]):
    class Meta:
        model: _M

it does not help much and I get the following errors

error: Type variable "main._M" is unbound  [valid-type]
            model: _M
                   ^
error: _M? has no attribute "some_base_class_method"  [attr-defined]
            self.Meta.model.some_base_class_method()
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~