【发布时间】:2011-04-12 07:55:40
【问题描述】:
无论出于何种原因,当我刚接触 Python 和 Django 时,我在 models.py 文件的顶部写了一些类似这样的导入语句:
from django.contrib import auth
我会这样使用它:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.User)
# ...
这很好用。很久以后,我写了一个自定义管理命令,它会这样做:
from myapp.models import MyModel
当我运行我的自定义命令 (python manage.py my_command) 时,这将导致 Python 抱怨模块 auth 在 models.py 中声明 ForeignKey 的行上没有属性 models。
为了解决这个问题,我将我的 models.py 更改为更常用的:
from django.contrib.auth.models import User
class MyModel(models.Model):
user = models.ForeignKey(User)
# ...
有人可以向我解释我缺少什么吗?运行管理命令时,环境中有什么不同吗?还是我一直都做错了?谢谢!
编辑:根据 dmitko 对循环导入的预感,以下是我的 models.py 文件中使用的导入。我展示了注释掉的 auth 的原始导入,以及唯一具有 auth 用户模型外键的模型:
import datetime
from django.db import models
# from django.contrib import auth
from django.contrib.auth.models import User
class UserLastVisit(models.Model):
# user = models.ForeignKey(auth.models.User, unique=True)
# ^^^^^^^^^^^^^^^^
# after adding mgmt command, error occurred here; change to the line below
user = models.ForeignKey(User, unique=True)
last_visit = models.DateTimeField(db_index=True)
以下是发现问题的管理命令的导入:
import datetime
from django.core.management.base import NoArgsCommand
from core.models import UserLastVisit, AnonLastVisit, Statistic
这是设置循环导入类型的情况吗?
【问题讨论】: