Skip to content

More context for schema validation #1421

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

Open
madisvain opened this issue Mar 13, 2025 · 0 comments
Open

More context for schema validation #1421

madisvain opened this issue Mar 13, 2025 · 0 comments

Comments

@madisvain
Copy link

The request object is available as context for Schema validation of the incoming request. But there are cases where you would need more context based on the request to make the validation.

For example on of such cases is a PUT or PATCH request where you need access to the instance that is being updated. Incoming data validation happens so early that I have not found a way of adding extra context currently.

What I currently do is get the object ID from the context -> request.resolver_match.kwargs and fetch the object during validation.

@model_validator(mode="after")
    def validate_no_overlapping_leaves(self, info: ValidationInfo) -> "LeaveUpdateSchema":
        # TODO: see if path_params could be added to context in Django ninja
        # https://github.com/vitalik/django-ninja/blob/master/ninja/params/models.py#L68
        path_params = info.context["request"].resolver_match.kwargs
        instance = Leave.objects.filter(id=path_params["leave_id"]).first()

        if instance:
            # Check if there are any overlapping leaves for the same employee, excluding the current leave

        return self

I found that when the request is attached to the context in ParamModel resolve actually path_params is available. It's just not passed as context. It would be a minimal change but allow additonal context data for the validators.

I would be happy to prepare a PR for this if the idea finds support.

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