[Fixed]-Can we repackage and break models in multiple classes and packages in Django 1.8?

1👍

The trick here is that you cannot directly replace:

models.py
    class ModelOne(...):
        ...
    class ModelTwo(...):
        ...

with:

/models
    model_one.py
        class ModelOne(...):
            ...
    model_two.py
        class ModelTwo(...):
            ...

as now from models import ModelOne will fail, Python doesn’t know how to find ModelOne within the directory. One fix is to change the imports, to e.g.

from models.model_one import ModelOne

but this may mean lots of changes throughout your app; it’s much easier to use an __init__.py to determine what should be importable from models, making the directory a package that appears to Python to be identical to the single file you had before:

/models
    __init__.py
       from model_one import ModelOne
       from model_two import ModelTwo
    model_one.py
        class ModelOne(...):
            ...
    model_two.py
        class ModelTwo(...):
            ...

See e.g. https://docs.python.org/2/tutorial/modules.html#packages for more information.

Leave a comment