我已经将我的模型文件重构为一个模块 - 这样就可以更容易地维护代码,因为它已经增长了很多。
有趣的是,它不适用于引用另一个引用其中第一个类的类中的一个类:
UPD:循环引用令人困惑的python,这就是问题所引起的。当仅引用模型定义中的其他模型时,这很容易解决。但是,Picture具有引用paperType类的方法,反之亦然 - 如何修复它?
这是班级图片:
from django.db import models
from django.utils import simplejson
from picviewer.models import Collection, ImageSizeRatio, printSize
class Picture(models.Model):
name = models.TextField(null=False,blank=False,unique=False)
collection = models.ForeignKey(Collection)
popularity = models.IntegerField(default=0,unique=False)
isPurchasable = models.BooleanField(default=False)
allowBuyExclusive = models.BooleanField(default=False)
basePrice = models.DecimalField(decimal_places=2,max_digits=8)
imageSizeRatio = models.ForeignKey(ImageSizeRatio)
imageThumbnail = models.FileField(upload_to='pictures')
imagePreview = models.FileField(upload_to='pictures')
imageSmall = models.FileField(upload_to='pictures')
imageNormal = models.FileField(upload_to='pictures')
imageLarge = models.FileField(upload_to='pictures')
imageHuge = models.FileField(upload_to='pictures')
allowedPrintSize = models.ManyToManyField(printSize)
这是它引用的printSize类 - 你看到它调用Picture函数来对指定printSize的图片做一些数学运算:
from django.db import models
from picviewer.models import paperType
from picviewer.models import Picture
class printSize (models.Model):
name = models.CharField(null=False,blank=False,unique=True,max_length=60)
width = models.IntegerField(null=False,blank=False)
height = models.IntegerField(null=False,blank=False)
allowedPaperType = models.ManyToManyField(paperType)
#isActive = models.NullBooleanField(null=True, default=None)
def json(self, picture_id, base_price):
sizes_selector = printSize.objects.filter(picture__id = picture_id)
sizes = list()
for size in sizes_selector:
papers = list()
for paper in size.allowedPaperType.all():
cost_for_paper = Picture.objects.get(id=picture_id).calculatePrice(paper.id,size.id)
p = dict(id = paper.id,
name = paper.name,
description = paper.description,
price = paper.pricePerSqMeter.__str__(),
cost = "%.2f" % cost_for_paper)
papers.append(p)
s = dict(id = size.id,
name = size.name,
width = size.width,
height = size.height,
allowedPapers = papers)
sizes.append(s)
return sizes
现在这是我在shell中尝试导入Picture:
>>> from picviewer.models import Picture
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\~Sasha\eclipse_workspace\zavalen\picviewer\models\Picture.py", line 4, in <module>
from picviewer.models import Collection, ImageSizeRatio, printSize
File "D:\~Sasha\eclipse_workspace\zavalen\picviewer\models\printSize.py", line 4, in <module>
from picviewer.models import Picture
ImportError: cannot import name Picture
>>>
我能解决这个问题吗? :)
答案 0 :(得分:26)
要避免循环导入,请将FK模型指定为字符串,例如
collection = models.ForeignKey('Collection') # Collection is in the same module
或
collection = models.ForeignKey('myapp.Collection') # Collection is in another app