How to fix sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres

Problem

When running a Python application that uses SQLAlchemy or SQLModel, you might encounter the following error:

...
  File "/usr/local/lib/python3.10/dist-packages/sqlalchemy/util/deprecations.py", line 281, in warned
    return fn(*args, **kwargs)  # type: ignore[no-any-return]
  File "/usr/local/lib/python3.10/dist-packages/sqlalchemy/engine/create.py", line 550, in create_engine
    entrypoint = u._get_entrypoint()
  File "/usr/local/lib/python3.10/dist-packages/sqlalchemy/engine/url.py", line 758, in _get_entrypoint
    cls = registry.load(name)
  File "/usr/local/lib/python3.10/dist-packages/sqlalchemy/util/langhelpers.py", line 375, in load
    raise exc.NoSuchModuleError(
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres

Solution

This error occurs when you’re using a bad database URL:

Your database URL looks like this:

postgres://user:password@localhost/database

but the scheme part needs to be postgresql, not postgres.

postgresql://user:password@localhost/database