简体   繁体   中英

Py2neo create node from object

Can someone help me with how to create a node from an object? eg we have object schema something like

class Person:
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

and I want to create py2neo Node Node("Person", name="John", surname="Doe") , however, I want to generalize this so I can use it with multiple schemas to something like Node(type(obj), **obj) but actually working.

For now, I've solved it like this:

    def create(self, obj):
        obj_props = {}
        for property, value in vars(obj).items():
            obj_props[property] = value

        node = Node(type(obj).__name__, **obj_props)
        tx = self.graph.begin()
        tx.create(node)
        tx.commit()

However, if anyone has a better solution I'm willing to learn.

Try using the py2neo.ogm module, as this is exactly what it is intended for. There are details of this in the docs.

You could change your creation logic to:

def create_node(obj):
    return Node(type(obj).__name__, **obj.__dict__)

Saving stays the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM