py2neo.ogm中GraphObject的动态属性

时间:2019-07-12 11:12:52

标签: python neo4j py2neo

使用py2neo的ogm模块,您可以在neo4j中为节点构建对象:

class Person(GraphObject):
    __primarykey__ = 'name'

    name = Property()

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


peter = Person('peter')

graph.create(peter)

是否可以向Person对象添加动态属性?

peter = Person('peter')

# this does not work
peter.last_name = 'jackson'

graph.create(peter)

可以先创建一个节点,然后再添加属性,但是创建具有动态属性的GraphObjects会更容易。

1 个答案:

答案 0 :(得分:0)

针对此问题,我想出了一种蛮力的解决方案:

翻出您的对象的类,将新属性添加到该类中,然后将其塞回到您的对象中,然后才意识到发生了什么:D

from py2neo.ogm import GraphObject, Property
from py2neo import Graph

class Person(GraphObject):
    __primarykey__ = "name"

    name = Property()

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

    def add_new_property(self, name, value):
        self.__class__ = type(
            type(self).__name__, (self.__class__,), {name: Property()}
        )
        setattr(self, name, value)


peter = Person("peter")
peter.add_new_property("lastname", "jackson")


g = Graph(host="localhost", user="neo4j", password="neo4j")
tx = g.begin()
tx.merge(peter)
tx.commit()

在此小型实验室设置中工作。但应在更复杂的环境中进行测试。

DZD的欢呼声:)

蒂姆