Skip to content

Instantly share code, notes, and snippets.

@frankwiles
Created March 7, 2023 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankwiles/0fe0b0b0beb1e9cc75e5d6fec5448849 to your computer and use it in GitHub Desktop.
Save frankwiles/0fe0b0b0beb1e9cc75e5d6fec5448849 to your computer and use it in GitHub Desktop.
Django string relationships to avoid circular imports
from django.db import models
from app1.models import ModelOne
from app2.models import ModelTwo
class ThingInThisApp(models.Model):
one = models.ForeignKey(ModelOne, related_name="things", on_delete.models.CASCADE)
two = models.ForeignKey(ModelTwo, related_name="things", on_delete.models.CASCADE)
# ...
from django.db import models
class ThingInThisApp(models.Model):
""" Removing the imports removes a ton of circular dependency issues """
one = models.ForeignKey("app1.ModelOne", related_name="things", on_delete.models.CASCADE)
two = models.ForeignKey("app2.ModelTwo", related_name="things", on_delete.models.CASCADE)
def some_method(self):
# In a pinch you can sometimes get away with importing in the method or function directly, but
# this is probably the least awesome way to do it
from other_app.models import Something
# use Something here
# If your issues are with utility functions just move them into another file and import the models. The issue is
# USUALLY related to models that import models which import models and that doesn't happen if you have a `utils.py` that
# is importing from 2-3 apps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment