Created
March 7, 2023 01:55
-
-
Save frankwiles/0fe0b0b0beb1e9cc75e5d6fec5448849 to your computer and use it in GitHub Desktop.
Django string relationships to avoid circular imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
# ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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