user3541631
user3541631

Reputation: 4008

avoid Circular import in Django

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(...)

Upvotes: 3

Views: 3518

Answers (1)

Alasdair
Alasdair

Reputation: 308839

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)

Upvotes: 11

Related Questions