Opened 4 years ago

Closed 4 years ago

#16511 closed Bug (invalid)

Problem with import and GFK

Reported by: rjdg@… Owned by: nobody
Component: contrib.contenttypes Version: 1.3
Severity: Normal Keywords: import, genericforeignkey, genericrelation
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello,

I have an error "Cannot import name <model name>" and find out why. It seems a bit strange so I report it as a bug.

Description:

We have two apps: x and y. And two Models: A (in x) and B (in y)

B has a generic foreign key
A has generic relation to B

I added this line to y.models:
from x.models import A

And Django raises error: "Cannot import name A" when I try to use python manage.py commands.
I needed this import line because I wanted to add third model - C in y.models, which would have a foreignkey to A

I've tested it also in a new empty django project and it works (hmm, in fact doesn't work) exactly that way.

Source:
x.models:
from django.db import models
from django.contrib.contenttypes import generic
from y.models import B

class A:

b_rel = generic.GenericRelation(B)

y.models:
from django.db import models
from django.contrib.contenttypes import generic
from x.models import A

class B:

content_object = generic.GenericForeignKey()

class C:

a = models.ForeignKey(A)

Removing import of A (and respectivly, the foreignkey to A in C) fixes the problem. I think it shouldn't be like that. I don't want to split application y to store C in separate file.

If it's a known problem I'm sorry, I've searched.

Attachments (2)

models.py (221 bytes) - added by rjdg@… 4 years ago.
x.models
models.2.py (227 bytes) - added by rjdg@… 4 years ago.
y.models

Download all attachments as: .zip

Change History (3)

Changed 4 years ago by rjdg@…

x.models

Changed 4 years ago by rjdg@…

y.models

comment:1 Changed 4 years ago by kmtracey

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

This is not a bug in Django, it's a straightforward circular import issue (and the message is from Python, not from Django). Django provides a way to do what's needed to avoid the circular import when you have interdependent models in different files (see https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.ForeignKey). Also, please post to django-users or try the #django IRC channel before assuming something you don't understand is a bug in Django; this tracker is not a support forum.

Note: See TracTickets for help on using tickets.
Back to Top