Michal Cikatricis
Michal Cikatricis

Reputation: 69

Py2neo create node from object

Can someone help me with how to create a node from an object? e.g. 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.

Upvotes: 0

Views: 184

Answers (3)

Lars
Lars

Reputation: 1969

You could change your creation logic to:

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

Saving stays the same.

Upvotes: 1

Nigel Small
Nigel Small

Reputation: 4495

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

Upvotes: 2

Michal Cikatricis
Michal Cikatricis

Reputation: 69

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.

Upvotes: 0

Related Questions