How to import the own model into myproject/alembic/env.py? How to import the own model into myproject/alembic/env.py? python-3.x python-3.x

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


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


Fiddling around few hours with this same issue, I found out a solution. First, this is my structure right now:

. ← That's the root directory of my project├── alembic.ini├── dev-requirements.txt├── requirements.txt├── runtime.txt├── setup.cfg├── src│   └── models│       ├── base.py│       ...│       └── migrations│           ├── env.py│           ├── README│           ├── script.py.mako│           └── versions│          └── tests

in env.py I simply did this:

import sysfrom os.path import abspath, dirnamesys.path.insert(0, dirname(dirname(dirname(abspath(__file__))))) # Insert <.>/srcimport models # now it can be importedtarget_metadata = models.base.Base.metadata

Hope you find this useful! :)

EDIT: I then did my first revision with the database empty (with no tables yet), alembic filled everything automatically for upgrade() and downgrade(). I did that in this way because not all my tables were automagically detected by alembic.


Put this in your env.py to put the working directory onto the Python path:

import sysimport ossys.path.insert(0, os.getcwd())