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

I want to use alembic revision --autogenerate with my own model classes. Because of this, I need to import them into myproject/alembic/env.py as described in the docs . But this does not work, even if I tried many options.

I am not sure in what context (I don’t know if this is the right word) alembic starts env.py Perhaps this causes some errors.

This is the directory and file structure that I use.

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

The error is that

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

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

+6
source share
2 answers

Starting a few hours with the same problem, I found a solution. Firstly, this is my structure right now:

 . ← That 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 just did this:

 import sys from os.path import abspath, dirname sys.path.insert(0, dirname(dirname(dirname(abspath(__file__))))) # Insert <.>/src import models # now it can be imported target_metadata = models.base.Base.metadata 

Hope you find this helpful! :)

EDIT: Then I did my first revision with an empty database (no tables), alembic automatically populated everything for upgrade() and downgrade() . I did it this way because not all of my tables were automatically detected using alembic.

+4
source

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

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

Then you can use the β€œnormal” import in your enb.py, related to your root folder, in your example:

 from src.models.base import Base 
+3
source

All Articles