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

Allow Schema model_config.extra = "allow"

Open soccer99 opened this issue 1 year ago • 5 comments

Allow setting the model_config key extra="allow"

# schemas.py

class ExtraAllowedSchema(Schema):
    name: str

    class Config(Schema.Config):
        extra = "allow"

# views.py
@api.post("/extra")
def extra_params(request, payload: ExtraAllowedSchema):
    """
    Test that a Schema with model_config.extra = "allow" will allow keys not defined in schema
    """
    return payload

A request with extra keys will be honored and returned

# Request
POST: /extra
JSON payload {"name": "my name", "age": 100}
Response
{"name": "my name", "age": 100}

Also works on response schemas if you return a dictionary with extra keys outside your OutSchema.

Fixes issue: https://github.com/vitalik/django-ninja/issues/1087

soccer99 avatar Feb 28 '24 06:02 soccer99

This change causes extra fields to be included in the main parsed data - clearly not what we want. We need the extra data stored in the model_extra attribute.

p-baum avatar Mar 04 '24 09:03 p-baum

This change causes extra fields to be included in the main parsed data - clearly not what we want.

Not really. It's ok.

Vulwsztyn avatar Mar 05 '24 17:03 Vulwsztyn

Including the extra fields at the top level is the default pydantic behavior when using extra = "allow". I suppose we could only expose those extra fields in an extra param on the view function if thats what is decided.

soccer99 avatar Mar 05 '24 19:03 soccer99

@vitalik Could you take a look?

I'm sorry if it is not ok that I ping you, but I'm interested in this feature

Vulwsztyn avatar Mar 27 '24 22:03 Vulwsztyn

Still thinking about it (need more testing on like how it will behave wit schema have resolvers or handles objects outputs instead of dicts...)

vitalik avatar Apr 30 '24 12:04 vitalik