I'm trying to add a post_save Signal in my Django app and am running into a circular import issue.
helpers.py
from tracker.models import Record
def get_account_id(name):
return name + '123'
models.py
from helpers import get_account_id
class Record(models.Model):
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=120, blank=True)
matched_account_id = models.CharField(max_length=120, unique=False, blank=True)
def find_matched_account(sender, instance, *args, **kwargs):
instance.matched_account_id = get_account_id(instance.name)
instance.save()
pre_save.connect(find_matched_account, sender=Record)
This is obviously a simplification but sums up the issue I'm running into. I could move the code in helpers into models but would prefer to store things like this in helpers because I'll end up using it in other places.
Move the import into the function.
edit: submitted this a bit prematurely :P
When your imports are at the top of a file, they are executed as soon as that file is imported. That causes this type of error.
You can limit your imports to a function's scope to avoid this issue.
When you run into this issue, you should at least double check that your architecture is really appropriate. It is sometimes (but certainly not always) an indication that your architecture can be improved.
I find that you can usually move the function from the model to helpers, and make the first argument of the function be an instance of the model. That way, you'll just have a helper importing a helper.
(second edit: removed example code, which made no sense)