如何使用 py2neo.ogm (v3) 为不同类型的节点创建双向关系?
How do I create bidirectional relationships using py2neo.ogm (v3) for different types of nodes?
我是 py2neo ogm 的新手。我设置了两种类型的节点:User & Post。 Post 有发布者的 user_id,并且有日志显示用户何时看到 post。所以图表看起来像这样:
(:Post)-[:published_by]->(:用户),
(:用户)-[:浏览量]->(Post)
但我无法使用 py2neo ogm 对双向性质进行建模。我只能通过在 post 之前为用户定义 class 来将 post 与用户相关联,反之亦然。
我是这样写模型的:
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")
因为 Post class 写在 User 之后,如果我取消注释 'views' 关系,我会得到一个错误,因为我试图在之前引用 Post定义它。
我不确定 python 中是否有可以用来解决引用问题的东西,或者 ogm 中是否有另一个不同的关系对象可以用于双向关系?
好的,我明白了。我必须简单地在 Post class 中提供传入关系并将其用于引用其关系。
代码如下:
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")
查看哪些用户查看了post:
p = Post.select(graph).first()
rel = p.viewed_by
print(list(rel))
我是 py2neo ogm 的新手。我设置了两种类型的节点:User & Post。 Post 有发布者的 user_id,并且有日志显示用户何时看到 post。所以图表看起来像这样:
(:Post)-[:published_by]->(:用户), (:用户)-[:浏览量]->(Post)
但我无法使用 py2neo ogm 对双向性质进行建模。我只能通过在 post 之前为用户定义 class 来将 post 与用户相关联,反之亦然。
我是这样写模型的:
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")
因为 Post class 写在 User 之后,如果我取消注释 'views' 关系,我会得到一个错误,因为我试图在之前引用 Post定义它。
我不确定 python 中是否有可以用来解决引用问题的东西,或者 ogm 中是否有另一个不同的关系对象可以用于双向关系?
好的,我明白了。我必须简单地在 Post class 中提供传入关系并将其用于引用其关系。
代码如下:
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")
查看哪些用户查看了post:
p = Post.select(graph).first()
rel = p.viewed_by
print(list(rel))