Back to snippets

neomodel_person_country_node_creation_and_relationship_query.py

python

Defines a simple Person model with a relationship to a Country and demonstrates

Agent Votes
1
0
100% positive
neomodel_person_country_node_creation_and_relationship_query.py
1from neomodel import StructuredNode, StringProperty, RelationshipTo, config
2
3# Set the connection URL
4config.DATABASE_URL = 'bolt://neo4j:password@localhost:7687'
5
6class Country(StructuredNode):
7    code = StringProperty(unique_index=True, required=True)
8
9class Person(StructuredNode):
10    name = StringProperty(unique_index=True)
11    
12    # Traverse to the Country node
13    country = RelationshipTo(Country, 'IS_FROM')
14
15# Create a person and a country
16jim = Person(name='Jim').save()
17germany = Country(code='DE').save()
18
19# Connect them
20jim.country.connect(germany)
21
22# Querying
23germany_node = Country.nodes.get(code='DE')
24for person in germany_node.person.all():
25    print(f"{person.name} is from {germany_node.code}")