I have a Django project structured like so:
appname/
models/
__init__.py
a.py
base.py
c.py
... where appname/models/__init__.py contains only statements like so:
from appname.models.base import Base
from appname.models.a import A
from appname.models.c import C
... and where appname/models/base.py contains:
import django.db.models
class Base(django.db.models.Model):
...
and where appname/models/a.py contains:
import appname.models as models
class A(models.Base):
....
...and similarly for appname/models/c.py, etc..
I am quite happy with this structure of my code, but of course it does not work, because of circular imports.
When appname/__init__.py is run, appname/models/a.py will get run, but that module imports "appname.models", which has not finished executing yet. Classic circular import.
So this supposedly indicates that my code is structured poorly and needs to be re-designed in order to avoid circular dependency.
What are the options to do that?
Some solutions I can think of and then why I don't want to use them:
- Combine all my model code into a single file: Having 20+ classes in the same file is a far worse style than what I am trying to do (with separate files), in my opinion.
- Move the "Base" model class into another package outside of "appname/models": This means that I would end up with package in my project that contains base/parent classes that should ideally be split into the packages in which their child/sub classes are located. Why should I have base/parent classes for models, forms, views, etc. in the same package and not in their own packages (where the child/sub classes would be located), other than to avoid circular imports?
So my question is not just how to avoid circular imports, but to do so in a way that is just as clean (if not cleaner) that what I tried to implement.
Does anyone have a better way?