Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subclassing generic serializer #669

Open
H4rryK4ne opened this issue Sep 20, 2024 · 0 comments
Open

Subclassing generic serializer #669

H4rryK4ne opened this issue Sep 20, 2024 · 0 comments

Comments

@H4rryK4ne
Copy link

H4rryK4ne commented Sep 20, 2024

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()
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant