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

Using PostgresDsn for database settings parsing broken on Pydantic 2.10.0 onward #35

Open
attevaltojarvi opened this issue Jan 8, 2025 · 0 comments

Comments

@attevaltojarvi
Copy link

attevaltojarvi commented Jan 8, 2025

Hi,

after upgrading my Pydantic version to 2.10.x, I noticed that my Pydjantic settings for my project prevent it from starting up. This is my settings definition:

class DatabaseSettings(pydjantic.BaseDBConfig):
    default: t.Annotated[
        pydantic.PostgresDsn, pydantic.Field(
            validation_alias='DATABASE_URL',
            json_schema_extra={'test_options': {'MIGRATE': False}}
        )
    ]
    
class DjangoSettings(BaseSettings):
    DATABASES: DatabaseSettings = DatabaseSettings()

The crash happens in django.db.utils, in the configure_settings method, where the line conn.setdefault("ATOMIC_REQUESTS", False) raises AttributeError: 'PostgresDsn' object has no attribute 'setdefault'.

This seems to be due to a Pydantic internal change (I'm suspecting this PR: pydantic/pydantic#10662), causing the if not isinstance(value, (str, MultiHostUrl)): check to be hit in the field validator method of the BaseDBConfig class, and the value, the PostgresDsn instance, being returned as-is. Apparently there's some inheritance change.

This can be prevented by importing the private base class from which PostgresDsn currently inherits from and adding it in the tuple:

from pydantic.networks import _BaseMultiHostUrl


class BaseDBConfig(BaseSettings):
    ...
    
    @field_validator('*')
    def format_config_from_dsn(cls, value: Any, info: ValidationInfo):
        if value is None:
            return {}

        if not isinstance(value, (str, MultiHostUrl, _BaseMultiHostUrl)):
            return value
    ....

but of course that's not an exhaustive solution.

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