Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
Circular import between models and helpers in Django

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!