About Avoiding Model Imports in Models.py
Avoid model imports from other apps in models.py
to ensure that there are no circular imports and that the model register works correctly in Django.
For relations, use the string syntax like this:
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:
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 5.x Django 4.2 Django 3.2 Python 3
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.