Python 无法导入名称

标签 python python-2.7

我似乎不知道如何相互导入两个类。运行应用程序时,它只会显示

  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)

这完全绕过了导入问题。

来自ListField docstring :

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/

相关文章:

python - Centos 6 中使用 SCL Python 2.7 的 Ansible 加密警告

python - Ubuntu 中的 pip 版本不同

python - 打印嵌套数组的更好方法

python - python中的Keras序列分类

python - 通过 Django REST Framework list_route 使用单个 URL 进行 GET 和 POST

python - 让 Python 代码更有效地减少脚本大小?

python - 函数恰好需要 2 个参数(给定 4 个)

python - 如何根据另一列的值替换一列的 NaN 值?

python - 将一个复杂的字符串 ('2,3-5,50-60,70' ) 分解到列表中

python - 如何压缩两个字符串?