django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

Update pydantic model Config classes

Open adamchainz opened this issue 2 years ago • 4 comments

Update Schema class and subclasses for the pydantic config changes from its version 2.

I stopped part way since I realized the changes affect the API. Do you think using model_config makes sense for subclasses, or would you go with another design like ModelSchema.Meta?

adamchainz avatar Nov 21 '23 23:11 adamchainz

Hi @adamchainz

yeah, I'm still thinking about this... (see also discussion here #934 )

basically Pydantic wants to put stuff to model_config, while Django people are very familiar with class Meta

maybe the most optional solution would be to allow users to set pydantic settings in Meta and then copy them to model_config on class creation

vitalik avatar Nov 22 '23 11:11 vitalik

I think there should be minimal django ninja for wrapping pydantic and use the pydantic primitive. Otherwise users need to know django-ninja + pydantic. But on average users are going to be much more familiar with pydantic as it's widely used, I like @adamchainz approach

jkgenser avatar Dec 05 '23 01:12 jkgenser

@jkgenser

but what do you mean by adamchainz's approach ?

to have all handled by Meta:


class SomeData(ModelSchema):
     class Meta:
           model = User
           fields = '__all__'
           alias_generator=to_camel # < this is a pydantic setting

or split with model_config:

class SomeData(ModelSchema):
     model_config = ConfigDict(alias_generator=to_camel)
     class Meta:
           model = User
           fields = '__all__'

vitalik avatar Dec 05 '23 13:12 vitalik

My two cents here. I dislike Meta class approach in django. It's quite common that you have a BaseClass with it's own Meta class. Then you create a custom model/schema and inherit the BaseClass. If you then create a new Meta class in this new model, it's quite easy to forget inheritance of meta class from parent.

Example:

class BaseSchema(Schema):
    field: str
    
    class Meta:
        config = ConfigDict(populate_by_name=True, alias_generator=to_camel)


class UserSchema(BaseSchema):
    name: str
    class Meta:
        __fields__ = ["name"]

In this case, the Meta class in BaseSchema will be ignored.

KlemenS189 avatar Feb 27 '24 10:02 KlemenS189