我读到这与循环依赖项有关,但我真的找不到解决办法。我正在尝试获取用户的数量(属于一个组织),可能还有一些与用户相关的更多细节,但我似乎无法在Organization模型中真正使用用户模型。
我还试图像get_users_count一样逆转return self.user_set.count(),但这也不起作用。
溯源
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Manos/Projects/devboard/project/accounts/models.py", line 3, in <module>
from project.organizations.models import Organization
File "/Users/Manos/Projects/devboard/project/organizations/models.py", line 5, in <module>
from project.accounts.models import User
ImportError: cannot import name User组织模型
from uuidfield import UUIDField
from django.db import models
from project.accounts.models import User
class Organization(models.Model):
id = UUIDField(primary_key=True, auto=True, db_index=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=200, unique=True)
website = models.URLField(max_length=200, blank=True)
def __str__(self):
return self.name
def get_users_count(self):
return User.objects.filter(organization=self).count()用户模型
class User(AbstractBaseUser):
id = models.AutoField(primary_key=True) # custom User models must have an integer PK
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
organization = models.ForeignKey(Organization, related_name="users", null=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)发布于 2015-03-29 03:11:04
将导入移到get_users_count()方法中:
def get_users_count(self):
from project.accounts.models import User
return User.objects.filter(organization=self).count()或完全删除导入并使用反向关系:
def get_users_count(self):
return self.users.count()https://stackoverflow.com/questions/29325198
复制相似问题