vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
6.59k stars 396 forks source link

Custom baseclass for ModelSchema without a model specified #995

Open jrocketfingers opened 7 months ago

jrocketfingers commented 7 months ago

I'd like to create a baseclass that enforces alias_generator = to_camel, but I can't seem to dance around the ModelSchema metaclass expectation of meta.model being specified.

The naïve approach I've tried was:

class BaseModelSchema(ModelSchema):
    class Meta(ModelSchema.Meta):
        alias_generator = to_camel

In addition to that, I tried a few ways to replace the metaclass with the ABCMeta, but it didn't seem to work.

Has anyone done something like this? Is it foolish to do so? Maybe I should just focus on creating a Meta class to inherit?

jozekuhar commented 6 months ago

Curently I am doing it like this:

class CamelCase(Schema):
    model_config = ConfigDict(alias_generator=to_camel_case, populate_by_name=True)
class ColorSchema(CamelCase, ModelSchema):
    class Meta:
        model = Color
        fields = "__all__"

But it would be cleaner if I could just create subclass of ModelSchema with same config as CamelCase class.