Tuesday, November 30, 2010

Re: Issues importing models in between apps

On Nov 30, 6:01 am, Victor Hooi <victorh...@gmail.com> wrote:
> Hi,
>
> I had an application with a fairly large models.py file, which I split
> up into separate apps to make it easier to manage.
>
> Two of the apps are called "conferences" and "people", each with their
> own models.py.
>
> These two are fairly tightly entwined, they each refer to each other.
>
> At the top of project_name/conferences/models.py, I have:
>
>     from django.db import models
>     from nextgen.people.models import Person
>
> At the top of project_name/people/models.py, I have:
>
>     from django.db import models
>     from project_name.conferences.models import Conference
>
> However, when I try to run ./manage.py validate, it gives me an error:
>
>       File "/sites/.virtualenvs/project_name/src/django/django/utils/
> importlib.py", line 35, in import_module
>         __import__(name)
>       File "/home/victorhooi/djangoProjects/project_name/../
> project_name/conferences/models.py", line 2, in <module>
>         from project_name.people.models import Person
>       File "/home/victorhooi/djangoProjects/project_name/../
> project_name/people/models.py", line 3, in <module>
>         from project_name.conferences.models import Conference
>     ImportError: cannot import name Conference
>
> I'm not sure why this is happening - from the looks of it, it's
> opening up conferences/models.py, then importing people.models.Person
> from there, which inside of that tries to import Conference - is it
> somehow clashing?
>
> Or is there a better way of creating multiple apps that all share
> models? The main reason I split it up was for logically separating all
> the different models, they still all need to import/relate to each
> other.
>
> Cheers,
> Victor

You have a circular dependency between conferences.models and
people.models - each file is trying to import the other one before it
can continue. Obviously, there's no way they can both depend on the
other.

The solution is not to import them at all. Usually the only reason to
do so is to refer to a model in the other module in a ForeignKey - but
you can use a variation of the string syntax to avoid this completely:

class Person(models.Model):
conferences = models.ManyToManyField('conferences.Conference')

--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment