我似乎不知道如何相互导入两个类。运行应用程序时,它只会显示
from room import Room
ImportError: cannot import name Room
这可能是一个设计问题,但我认为没有其他方法来引用这两个类,所以这需要保持原样。需要导入的唯一原因是对象中的 redisco 模块需要它们(它们需要知道类型)
#Room class.
class Room(models.Model):
from player import Player
players = models.ListField(Player, required = True)
#Player class
class Player(models.Model):
from room import Room
room = models.ReferenceField(Room, required = True)
如何让它发挥作用?
E:
框架是Redisco (Redis)
最佳答案
大多数 ORM 模型要么支持反向引用(其中引用字段的目标模型被赋予指向回引用对象的额外属性),和/或允许您通过其他方式指定关系。
Redisco 没有我能发现的反向引用,但它确实支持字符串引用。如果您传入一个字符串,它将被解释为模型名称,与 __name__
属性匹配:
class Room(models.Model):
players = models.ListField('Player', required = True)
这完全绕过了导入问题。
target_type -- can be a Python object or a redisco model class.
If target_type is not a redisco model class, the target_type should also a callable that casts the (string) value of a list element into target_type. E.g. str, unicode, int, float.
ListField also accepts a string that refers to a redisco model.
code to resolve the name使用函数get_model_from_key()
解析字符串,它只是搜索 models.Model
的所有子类,匹配 __name__
。
它会在验证新值或首次检索现有值时解析名称,此时 Player
子类已导入。
关于Python 无法导入名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27694357/