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

Injected Context for Model Class not picked up #444

Open
lowmann15 opened this issue Apr 1, 2024 · 0 comments
Open

Injected Context for Model Class not picked up #444

lowmann15 opened this issue Apr 1, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@lowmann15
Copy link

Bug

Trying to use the validation context within one of my Model classes which pydantic offers is not possible.

Current Behavior

Example code to reproduce:

from odmantic import Model
from pydantic import ValidationInfo, field_validator


class MyModel(Model):
    text: str

    @field_validator('text')
    @classmethod
    def remove_stopwords(cls, v: str, info: ValidationInfo):
        context = info.context
        if context:
            stopwords = context.get('stopwords', set())
            v = ' '.join(w for w in v.split() if w.lower() not in stopwords)
        return v


data = {'text': 'This is an example document'}
print(MyModel.model_validate(data))  # no context
#> text='This is an example document'
print(MyModel.model_validate(data, context={'stopwords': ['this', 'is', 'an']}))
#> text='This is an example document'
print(MyModel.model_validate(data, context={'stopwords': ['document']}))
#> text='This is an example document'

Expected behavior

The output should not be

text='This is an example document'
text='This is an example document'
text='This is an example document'

but

text='This is an example document'
text='example document'
text='This is an example'

according to the context that should filter out the words per use case.

Environment

  • ODMantic version: 1.0.1
  • Pydantic infos (output of python -c "import pydantic.utils; print(pydantic.utils.version_info())):
 pydantic version: 2.6.4
        pydantic-core version: 2.16.3
          pydantic-core build: profile=release pgo=true
                 install path: /Users/lxr1046/Library/Caches/pypoetry/virtualenvs/clinical-etl-service-lM9J4W3w-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.8 (main, Feb  6 2024, 21:21:21) [Clang 15.0.0 (clang-1500.1.0.2.5)]
                     platform: macOS-14.4-arm64-arm-64bit
             related packages: fastapi-0.110.0 mypy-1.9.0 typing_extensions-4.10.0 pydantic-settings-2.2.1
                       commit: unknown

@lowmann15 lowmann15 added the bug Something isn't working label Apr 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant