0

I have two modules, like this:

--models.py

from myapp.filters import EntityFilter
class Entity(models.Model):
   //model definition

   def someMethod(self):
      entities = EntityFilter(...)

--filters.py

from myapp.models import Entity
class EntityFilter(django_filters.FilterSet):
    class Meta:    
        model = Entity
        // ...

Obviously I got error ImportError: cannot import name Entity

How should I reorganize my code?

What do you think about this solution? Is it OK?

class Entity(models.Model):
   //model definition

   def someMethod(self):
      from myapp.filters import EntityFilter
      entities = EntityFilter(...)

It works fine...

David Silva
  • 1,939
  • 7
  • 28
  • 60

2 Answers2

0

Has you try to do this?

from myapp.models import Entity
class EntityFilter(django_filters.FilterSet):
    class Meta:    
        model = 'Entity'
        // ...
emigue
  • 492
  • 3
  • 13
0

The method that you used to fix the problem is just fine and is quite common in python code that I've seen (at least when circular dependencies can't be avoided; it's also done to avoid over-polluting the global namespace when there aren't any circular dependencies to worry about). For a good description of how import statements work in python, and why your work-around solved the issue, see this site, referenced in the answer to the "Circular dependency in Python" question noted in the comment by @mata above: http://effbot.org/zone/import-confusion.htm.

mattg
  • 1,731
  • 1
  • 12
  • 20