3

I have two models Company and Actions:

from companies.models import Company

class Action(models.Model):

    company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE)

I have then an utility in utils.py

from .models import Action

def create_action(user, verb, target_name=None, target=None):
    action = Action(user=user, verb=verb, target=target)

This utility I called in Company model on def save, so on Company Model I have:

from not.utils import create_action 

so Action Model import Company Model as FK, utils import Action Model, and Company Model import utils

Now, because of circular import Django gives an error:

ImportError: cannot import name 'Company'

I saw some q/a here to use import directly (without from) I tried but didn't worked

import not.utils as nt
nt.create_action(...)

1 Answer 1

11

Remove the Company import from actions/models.py and use a string instead:

class Action(models.Model):
    company = models.ForeignKey('companies.Company', blank=True, null=True, related_name='activity', on_delete=models.CASCADE)
1
  • In the official Django documentation they use exactly this notion. This is the proper way of assigning relations.
    – cezar
    Commented Dec 20, 2017 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.