循环引用的Python问题:

时间:2010-10-31 21:05:43

标签: python circular-reference

我明白了:

ImportError: cannot import name Image (from image_blob.py)

请帮助我谢谢:s

我的代码:

image.py:

from google.appengine.ext import db
from app.models.item import Item

class Image(Item):
    # imports
    from app.models.image_blob import ImageBlob
    #from app.models.user import User
    #from list_user import ListUser # is needed in order to have the references

    # references
    #uploaded_by_user = db.ReferenceProperty(User, required = True)
    large_image = db.ReferenceProperty(ImageBlob, required = True)
    small_image = db.ReferenceProperty(ImageBlob, required = True)

    # image info
    title = db.StringProperty(required = True)
    description = db.StringProperty(required = False)

    # metadata


    # relations

image_blob:

from google.appengine.ext import db


class ImageBlob(db.Model):
    from app.models.image import Image

    data = db.BlobProperty(required = True)
    image = db.ReferenceProperty(Image, required = True)

1 个答案:

答案 0 :(得分:2)

您尝试在处理完整个image_blob.py之前从image.py导入。在from app.models.item import Item发生时,class Image尚未定义,因此尚未导入(整个类定义必须在符号实际上是定义的。)

有一个简单的解决方案:不要在image上定义ImageBlob属性。 AppEngine的模型自动为您定义向后引用,因此当您将ImageBlob添加到Image时,它会自动在ImageBlob上定义一个属性引用回引用它的Image集合(在当前用例中,应该是大小为1)。