About Avoiding Model Imports in Models.py

To be sure that there are no circular imports and model register works correctly in Django, avoid model imports from other apps in models.py.

For relations use the string syntax like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class MyModel(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        #...
    )
    categories = models.ManyToManyField(
        'categories.Category',
        #...
    )
    opposite = models.OneToOneField(
        'opposites.OppositeModel', 
        #...
    )
    #...

To use models from other apps in your model methods, import them at the method level:

1
2
3
4
5
def get_published_categories(self):
    from categories.models import Category
    return self.categories.filter(
        publishing_status=Category.STATUS_PUBLISHED,
    )

Tips and Tricks Programming Architecture Development Django 2.2 Django 1.11 Django 1.8