Milano Slesarik Milano Slesarik - 3 months ago 22
Python Question

How to avoid dependency injection in Django?

I'm trying to figure out how to avoid dependency injection in my project. There is a file

notifications.py
in app directory.

File
notifications.py
contains methods for sending emails to admin and users. To get admins email, I need to check object of
SystemData
model. But in models, I use notifications.

models

class SystemData(models.Model):
admin_alerts_email = models.EmailField(verbose_name=u'Emailová adresa admina')
contact_us_email = models.EmailField(verbose_name=u'Adresa kontaktujte nás')
waiting_threshold = models.PositiveSmallIntegerField(verbose_name=u'Maximálny počet minút čakania')

class SomeModel(models.Model):
....
def save(...):
notifications.send_message_to_admin('message')


notifications.py

from django.core.mail import EmailMessage
from models import SystemData

def send_message_to_admin(message):
mail = EmailMessage(subject, message, to=[SystemData.objects.all().first().admin_email])
mail.send()


Django returns that it can't import
SystemData
.

Do you know what to do?

EDIT:

stacktrace


stacktrace

Answer

You can solve circular dependencies in functions by using inline imports:

class SomeModel(models.Model):
    ....
    def save(...):
        from .notifications import send_message_to_admin
        send_message_to_admin('message')

This will delay the import statement until the function is actually executed, so the models module has already been loaded. The notifications module can then safely import the models module.

Comments