Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

341
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda