Django-圆形模型导入问题

2024-06-01 08:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的不明白,所以如果有人能解释这是怎么回事,我会非常感谢。我有两个申请,帐户和主题。。。这是我的设置列表:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'accounts',
    'themes',
)

在帐户中,我试图这样做:

from themes.models import Theme

class Account(models.Model):
    ACTIVE_STATUS = 1
    DEACTIVE_STATUS = 2
    ARCHIVE_STATUS = 3
    STATUS_CHOICES = (
        (ACTIVE_STATUS, ('Active')),
        (DEACTIVE_STATUS, ('Deactive')),
        (ARCHIVE_STATUS, ('Archived')),
    )

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)
    slug = models.SlugField(unique=True, verbose_name='URL Slug')
    status = models.IntegerField(choices=STATUS_CHOICES, default=ACTIVE_STATUS, max_length=1)
    owner = models.ForeignKey(User)
    enable_comments = models.BooleanField(default=True)
    theme = models.ForeignKey(Theme)
    date_created = models.DateTimeField(default=datetime.now)

在我的主题模型中:

class Theme(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)
    slug = models.SlugField(unique=True, verbose_name='URL Slug')
    date_created = models.DateTimeField(default=datetime.now)

class Stylesheet(models.Model):
    id = models.AutoField(primary_key=True)
    account = models.ForeignKey(Account)
    date_created = models.DateTimeField(default=datetime.now)
    content = models.TextField()

Django正在排除以下错误:

from themes.models import Theme
ImportError: cannot import name Theme

这是某种循环进口问题吗?我试过使用一个懒引用,但这似乎也不起作用!


Tags: djangonameimportidtruedefaultmodelmodels
3条回答

删除Theme的导入并将模型名称用作字符串。

theme = models.ForeignKey('themes.Theme')

我在任何地方都没有看到足够详细的内容,即在引用其他应用程序中的模型时,如何正确地在ForeignKey中构造字符串。这个字符串必须是app_label.model_name。而且,非常重要的是,app_label不是已安装应用程序中的整行,而是它的最后一个组件。因此,如果您安装的应用程序如下所示:

INSTALLED_APPS = (
...
    'path.to.app1',
    'another.path.to.app2'
)

然后,要在app1模型的app2中包含模型的外键,必须执行以下操作:

app2_themodel = ForeignKey('app2.TheModel')

我花了很长时间试图解决一个循环导入问题(所以我不能只是from another.path.to.app2.models import TheModel),在我无意中发现之前,google/so没有帮助(所有的例子都有单组件应用程序路径),所以希望这将帮助其他django新手。

至Django 1.7:

使用get_model中的django.db.models函数,该函数用于惰性模型导入

from django.db.models import get_model
MyModel = get_model('app_name', 'ModelName')

就你而言:

from django.db.models import get_model
Theme = get_model('themes', 'Theme')

现在您可以使用Theme

对于Django 1.7+:

from django.apps import apps
apps.get_model('app_label.model_name')

相关问题 更多 >