python – 使用django neomodel的以下模型
作者:互联网
我使用neo4j数据库和django-neomodel,
我想为我的用户实现一个Follow系统,并为用户编写这个模型:
class UserNode(StructuredNode):
user_id = IntegerProperty(required=True, index=True)
follow = RelationshipTo('UserNode','FOLLOW')
def get_followers(self):
results, metadata = self.cypher("START a=node({self}) MATCH a<-[:FOLLOW]-(b) RETURN b");
return [self.__class__.inflate(row[0]) for row in results]
def get_following(self):
results, metadata = self.cypher("START a=node({self}) MATCH b-[:FOLLOW]->(a) RETURN b");
return [self.__class__.inflate(row[0]) for row in results]
def follow_person(self, user_id):
import datetime
from django.utils.timezone import utc
followed_user = self.index.get(user_id=user_id)
self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow().replace(tzinfo=utc))})
self.save()
followed_user.save()
您认为我的UserNode模型适用于以下系统是一个很好的模型吗?
这个模型出现了问题!
当我运行此代码时:
a = UserNode.index.get(user_id=200)
b = UserNode.index.get(user_id=201)
c = UserNode.index.get(user_id=202)
a.follow_person(201)
b.follow_person(200)
print a.get_followers(), a.get_following()
输出是两个空列表.为什么?
解决方法:
你好neomodel的作者.
无需保存follow_person方法.
您使用的是哪个版本的neomodel?以下代码对我有用:
class UserNode(StructuredNode):
user_id = IntegerProperty(required=True, index=True)
follow = RelationshipTo('UserNode', 'FOLLOW')
def get_followers(self):
results, metadata = self.cypher("START a=node({self}) MATCH a<-[:FOLLOW]-(b) RETURN b")
return [self.__class__.inflate(row[0]) for row in results]
def get_following(self):
results, metadata = self.cypher("START a=node({self}) MATCH b-[:FOLLOW]->(a) RETURN b")
return [self.__class__.inflate(row[0]) for row in results]
def follow_person(self, user_id):
followed_user = self.index.get(user_id=user_id)
self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow())})
u1 = UserNode(user_id=1).save()
u2 = UserNode(user_id=2).save()
u1.follow_person(2)
u2.follow_person(1)
print "User 1 follows {}".format(u1.get_following())
print "User 1's followers {}".format(u1.get_followers())
您可能还需要考虑为传入和传入定义两个单独的关系管理器,这意味着您不需要编写密码查询:
class UserNode(StructuredNode):
user_id = IntegerProperty(required=True, index=True)
following = RelationshipTo('UserNode', 'FOLLOW')
followers = RelationshipFrom('UserNode', 'FOLLOW')
def follow_person(self, user_id):
followed_user = self.index.get(user_id=user_id)
self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow())})
print "User 1 follows {}".format(u1.following.all())
print "User 1's followers {}".format(u1.followers.all())
希望这可以帮助!如果您有任何问题,请随时给我发电子邮件.
标签:python,django,neo4j,graph-databases,cypher 来源: https://codeday.me/bug/20190725/1534288.html