Skip to main content
 首页 » 编程设计

Python 无法导入名称

2024年10月25日11Renyi-Fan

我似乎无法弄清楚如何将两个类相互导入。运行应用程序时,它只是说

  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 子类已被导入。