2013-06-02 55 views
2

我從Neo4j的數據庫和Django的neomodel, 使用我希望實現以下系統爲我的用戶,寫這種模式爲用戶:Django的一個下列型號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): 
     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模型以下系統是一個很好的模型?

和這個模型的問題occoured! 當我運行這段代碼:

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() 

輸出兩名空列表。爲什麼?

回答

5

你好,這裏是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()) 

您可能還需要考慮確定兩個獨立的客戶關係經理對未來出和傳入,這意味着你不需要寫CYPHER查詢:

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()) 

希望這可以幫助!如果您還有其他問題,請隨時給我發一封電子郵件。