erhosen-libs / pydjantic

Use Pydantic Settings in your Django application.
MIT License
37 stars 9 forks source link

Pydantic serializer warnings, such as "Expected `multi-host-url` but got `dict` - serialized value may not be as expected" #31

Closed earshinov closed 5 months ago

earshinov commented 9 months ago

Even when running tests:

tests/test_to_django.py::test_to_django_settings
  D:\NVIDIA\third-party\_python\pydjantic\.venv\Lib\site-packages\pydantic\main.py:308: UserWarning: Pydantic serializer warnings:
    Expected `multi-host-url` but got `dict` - serialized value may not be as expected
    return self.__pydantic_serializer__.to_python(

tests/test_db_config.py::test_dsn_and_exact_config
  D:\NVIDIA\third-party\_python\pydjantic\.venv\Lib\site-packages\pydantic\main.py:308: UserWarning: Pydantic serializer warnings:
    Expected `str` but got `dict` - serialized value may not be as expected
    return self.__pydantic_serializer__.to_python(

Seems to come from database configuration, e.g. (in test_dsn_and_exact_config):

class DatabaseConfig(BaseDBConfig):
    # declared as str, but actually deserialized as dict (Django database configuration)❓
    default: str = Field(default="postgres://user:password@hostname:5432/dbname")
    replica: PostgresDB = PostgresDB()

Applications still run, however:

erhosen commented 8 months ago

Hey @earshinov 👋🏻 Can you share your Django version?

earshinov commented 8 months ago

Hey @erhosen, sure!

Tests above are run with

I observe the same errors in my project, running

worldworm commented 5 months ago

Hi there 👋🏻

This may be a pragmatic approach and may not fix the root cause, but it will get rid of the warnings: Just set the type of your DatabaseConfig to str | dict or str | dict[str, Any]

class DatabaseSettings(BaseDBConfig):
    """https://docs.djangoproject.com/en/dev/ref/settings/#databases"""
    default: str | dict[str, Any] = Field(
        default=str(f"sqlite:///{BASE_DIR}/db.sqlite3"),
        validation_alias="DATABASE_URL",
        conn_max_age=0,
        ssl_require=False,
    )
    model_config = SettingsConfigDict(env_file=BASE_DIR / ".env")

(Tested with Python 3.10.12, Django 5.0.6, pydjantic 1.1.4)

I'm not sure if this might be confusing, but if you want I can do a quick pr to add this to the tests and demo.

erhosen commented 5 months ago

I'm not sure if this might be confusing, but if you want I can do a quick pr to add this to the tests and demo.

Thanks @worldworm, it would be nice to get rid of the warning!