Im very new to py2neo ogm. I have set up 2 types of nodes: User & Post. Post has the user_id of whoever has published it and there are logs which show when a user has seen a post. So the graph looks like this:
(:Post)-[:published_by ]->(:User), (:User)-[:views ]->(Post)
But I'm unable to model the bidirectional nature using py2neo ogm. I can only relate either post to user by defining the class for user before post or vice-versa.
I've written the models this way:
class User(GraphObject):
name = Property()
user_id = Property()
# views = RelatedTo(Post)
published = RelatedFrom("Post","PUBLISHED_BY")
class Post(GraphObject):
name = Property()
post_id = Property()
published_by = RelatedTo(User)
viewed_by = RelatedFrom("User","VIEWS")
Since Post class is written after User, if I uncomment 'views' relationship, I'll get an error because I'm trying to reference Post before defining it.
Im not sure if there's something in python that can used to resolve the reference issue or is there another a different relation object in ogm that can be used for bidirectional relationship?
Okay I figured this out. I have to simply provide an incoming relationship in Post class and use that for referring to its relationship.
Here's the code:
class User(GraphObject):
name = Property()
user_id = Property()
published = RelatedFrom("Post","PUBLISHED_BY")
class Post(GraphObject):
name = Property()
post_id = Property()
published_by = RelatedTo(User)
viewed_by = RelatedFrom(User,"VIEWS")
To see which users have viewed a post:
p = Post.select(graph).first()
rel = p.viewed_by
print(list(rel))