can't set relationship with neomodel in python

268 Views Asked by At

https://github.com/neo4j-contrib/neomodel/blob/5bc4213598233172526cd3c59fdfed5745a80130/doc/source/batch.rst#get_or_create

I'm running the following code:

class Dog(StructuredNode):
    name = StringProperty(required=True)
    owner = RelationshipTo('Person', 'owner')

class Person(StructuredNode):
    name = StringProperty(unique_index=True)
    pets = RelationshipFrom('Dog', 'owner')

bob = Person.get_or_create({"name": "Tom"})
bobs_gizmo = Dog.get_or_create({"name": "Gizmo"}, relationship=bob.pets)

tim = Person.get_or_create({"name": "Tim"})
tims_gizmo = Dog.get_or_create({"name": "Gizmo"}, relationship=tim.pets)

# not the same gizmo
assert bobs_gizmo[0] != tims_gismo[0]

tim = Person.get_or_create({"name": "Tim"})
tims_gizmo = Dog.get_or_create({"name": "Gizmo"}, relationship=tim.pets)

get this error:

Traceback (most recent call last):
  File "...", line 16, in <module>
    bobs_gizmo = Dog.get_or_create({"name": "Gizmo"}, relationship=bob.pets)
AttributeError: 'list' object has no attribute 'pets'

I've tried creating nodes and checked that basic functions work through neomodel.

1

There are 1 best solutions below

0
On

You can call the method get_or_create with more than one set of parameters, hence getting or creating multiple objects. That's why the method returns a list of objects. So in your code, as the error says, bob is a list. You only want the first item of this list:

bob = Person.get_or_create({"name": "Tom"})[0]
bobs_gizmo = Dog.get_or_create({"name": "Gizmo"}, relationship=bob.pets)

This is documented here: https://neomodel.readthedocs.io/en/latest/module_documentation.html#neomodel.core.StructuredNode.get_or_create and an example is provided here: https://neomodel.readthedocs.io/en/latest/batch.html#get-or-create

Edit the link you provided has been fixed in the master branch: https://github.com/neo4j-contrib/neomodel/blob/master/doc/source/batch.rst