Search code examples
django-modelsneo4jneo4django

copying / cloing neo4django model object


I was wondering whether there was a smart way to create an exact clone of a node in neo4django without having to copy every property and relationship manually.

p = Person.create(name="John Doe")
p.connect(...)

new_p = p 

won't work, as new_p won't be a clone (a new, individual node with same content), but rather a different pointer to the same node.


Solution

  • So do you need a new node in the graph, or a copy of the Django model?

    To create a copy with the same properties (but not the same relationships) and a new in-graph node, you could try something like

    p = Person.objects.create(name="John Doe")
    p2 = Person.objects.create(**p.node.properties)
    

    Doing the same thing with relationships is a little more difficult, but I've done it in the past and can write up a gist if that's what you need. Alternatively, this could also all be done in Gremlin or Cypher (with neo4django's helper functions) if that's a better fit, eg

    from neo4django.db import connection
    p = Person._neo4j_instance(connection.gremlin('results=<some code that yields a copied node>'))
    

    If you just need a copy of the Django model that's a different Python object (but still attached to the same node) you might try

    >>> p = Person.objects.create(name="John Doe")
    >>> p2 = Person.from_model(p)
    >>> print p2.name
    John Doe
    

    HTH!

    EDIT:

    How could I have forgotten- there's an included convenience method for this!

    >>> john = Person.objects.create(name="John Doe")
    >>> john_2 = john.copy_model()
    >>> john.name == john_2.name
    True
    

    Relationships and properties are all copied, though the returned model is unsaved- they don't share a node in the graph.

    Sorry about the run around, maybe this will be a little easier.