How to import the own model into myproject/alembic/env.py?

buhtz says get vaccinated picture buhtz says get vaccinated · Aug 16, 2015 · Viewed 7.1k times · Source

I want to use alembic revision --autogenerate with my own model classes. Because of that I need to import them in myproject/alembic/env.py as described in the docs. But this doesn't work even if I tried a lot of variations.

I am not sure in which context (don't know if this is the correct word) does alembic run the env.py. Maybe that causes some errors.

This is the directory and file structure I use.

myproject/
    common/
        __init__.py
        model.py
    alembic/
        env.py

The error is kind of that

    from .common import model
SystemError: Parent module '' not loaded, cannot perform relative import

myproject itself is just a repository/working directory. It is not installed into the system (with pip3, apt-get, easyinstall or anything else).

Answer

K. Norbert picture K. Norbert · May 22, 2016

You can set the PYTHONPATH environment variable to control what python sees as the top level folder, eg. if you are in the root folder of your project:

PYTHONPATH=. alembic revision -m "..."

Then you can use a "normal" import in your alembic env.py, relative to your root folder, in your example:

from src.models.base import Base