gpt4 book ai didi

python - django抽象模型继承导入

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:30 24 4
gpt4 key购买 nike

我想知道如何将抽象模型导入另一个应用程序

world_elements 拥有:

class Location(models.Model):
"""
Holds x,y coordinates of a virtual 2d map.
"""

x = models.IntegerField()
y = models.IntegerField()

class Meta:
abstract = True

def __unicode__(self):
return "%s, %s" % (self.x, self.y)

现在我在另一个应用程序中尝试:

from world_elements.models import Location

class NpcTown(Location):
"""
A town with their coordinates trianinggrounds quest office and all other relevant attributes
"""

# general town information
name = models.CharField(max_length = 63)
flavor = models.TextField(max_length = 511)
guild = models.ForeignKey(NpcGuild)

# locations
trainingground = models.ForeignKey(TrainingGround, null=True)

def __unicode__(self):
return self.name

但现在我得到 ImportError: cannot import name Location

如何导入抽象模型?

最佳答案

稍微简化类的名称,以下对我有用在 Django 1.7 中,这是当时最新的稳定版本写作。

目录布局

    project
\_ apps
\_ __init__.py
\_ A
\_ B
\_ config
\_ __init__.py
\_ settings.py
\_ urls.py
\_ wsgi.py
\_ data
\_ makefile
\_ manage.py
\_ README.md

在上面,app A 包含抽象模型。 B 使用它,因为如下:

抽象类

class AModel(Model):
...
class Meta:
abstract = True

然后

具体类

from apps.A.models import AModel

class BModel(AModel):
...
blah = "ayyo"

请注意,应用程序 A 和 B 都必须包含一个 __init__.py 文件。

不要害怕打破 Django 目录布局约定由 manage.py start{app,project} 强加。这样做会解放你的思想你会喜欢把东西整理得井井有条。

另一个有助于调试模块导入的东西就是 printing导入的模块。然后您可以知道实际正在解决的问题。例如:

from apps.A.models import AModel
print AModel # <class 'apps.A.models.AModel'>

和:

import apps
print apps # <module 'apps' from '/home/g33k/gits/checkouts/my/project/apps/__init__.pyc'>

关于python - django抽象模型继承导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com