Py2neo ogm基础知识:如何设置模型/导入

2024-06-01 07:57:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试(但失败)使用py2neov4。我实际上是想让this guidance跨python文件工作

在我的模型中,我有“设备”和“平台”。我将这两个对象分为两个文件:

# platform.py
from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom, Label
from .Equipment import Equipment

class Platform(GraphObject):
    __primarykey__ = "name"
    name = Property()
    quantity = Property()
    equipment = RelatedFrom(Equipment, "ENABLES")

    def as_json(self):
        self.printOut()
        res = {
            "name": self.name,
            "equipment": [b.name for b in self.equipment],
        }
        return res

    def __init__(self, name):
        super().__init__()
        self.name = name

以及

# Equipment.py
from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom, Label
from .Platform import Platform

class Equipment(GraphObject):
    __primarykey__ = "name"
    name = Property()
    platforms = RelatedTo(Platform, "ENABLES")

    def __init__(self, name):
        super().__init__()
        self.name = name

我的目标是迭代设备并将链接的相应平台打印为json:

equipment_matches = Equipment.match(graph)
for equipment_match in equipment_matches:
    for platform_node in equipment_match.platforms:
        print(platform_node.as_json())

我目前在循环导入之间徘徊(对于上面的代码): ImportError: cannot import name 'Platform' from 'ModuleName.Platform' 或者,当我按照其他示例将Platform设置为Equipment.py中的字符串时,我会得到一个不同的错误:AttributeError: module 'ModuleName.Equipment' has no attribute 'Platform'

是我遗漏了什么,还是py2neo不打算做我想做的事

编辑:到目前为止,我不确定的解决方案是,在init中,我编辑类如下:

from py2neo.ogm import RelatedFrom, RelatedTo
from .Equipment import Equipment
from .Platform import Platform

Platform.equipment = RelatedFrom(Equipment, "ENABLES")
Equipment.platforms = RelatedTo(Platform, "ENABLES")

这很管用,但我想知道有没有更友好的方法


Tags: namefromimportselfinitpropertyplatformenables