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

ModelSchema inheritance #1300

Open
Ksauder opened this issue Sep 19, 2024 · 0 comments
Open

ModelSchema inheritance #1300

Ksauder opened this issue Sep 19, 2024 · 0 comments

Comments

@Ksauder
Copy link
Contributor

Ksauder commented Sep 19, 2024

I would like to be able to inherit from ModelSchemas so I can add a configuration layer where I can add custom functionality to the underlying pydantic BaseModel and then inherit this ProjectModelSchema to create my model schemas. I believe the reason this functionality is broken is due to the underlying logic surrounding the use of create_schema in ModelSchemaMetaclass which stops any inheritance chain using ModelSchema. Multiple inheritance works in some cases, but I'd like to stay away from that.

Desire:

class ProjectModelSchema(ModelSchema):
    _custom_serializer = pydantic.model_serializer(mode="wrap")(_project_custom_serializer)

class ItemModelSchema(ProjectModelSchema):
    # custom serializer is inherited
    customfield: Optional[str] = None

    class Meta:
        model = Item
        fields = ["id", "name"]

class ChildItemModelSchema(ItemModelSchema):
    # custom serializer and custom field are inherited
    class Meta(ItemModelSchema.Meta):
        model = SubItem
        fields = ItemModelSchema.Meta.fields + ["childfield"]

Problems:

  1. You actually can't inherit from ModelSchema more than one deep. Example:
class ItemModelSchema(ModelSchema):
    class Meta:
        model = Item
        fields = ["id", "slug"]

class ChildItemModelSchema(ItemModelSchema):
    # this Meta is completely ignored
    class Meta:
        model = Item
        fields = ["id", "slug", "name"]
  1. You cannot currently create a ModelSchema class without specifying an internal Meta class which completely blocks the desired inheritance without multiple inheritance.

If I missed something please point it out.

@Ksauder Ksauder mentioned this issue Sep 20, 2024
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant