Google App Engine - 多个 child/parent

Google App Engine - Multiple child/parent

我想交朋友系统有这样的数据库模型:

class Users(ndb.Model):
    username = ndb.StringProperty(required = True)
    bio = ndb.StringProperty()

class friend_list(ndb.Model):
    list = ndb.StringProperty(repeated=True)

class friend_pending(ndb.Model):
    list = ndb.StringProperty(repeated=True)

friend_pending为尚未接受的朋友代言。而 friend_list 是被接受的朋友的模型。

我想让 friend_list 和 friend_pending 都成为 Users 实体的子实体。可能吗?

如果不可能的话,这是第二种方法:

    class Users(ndb.Model):
        username = ndb.StringProperty(required = True)
        bio = ndb.StringProperty()

    class friend_list(ndb.Model):
        user_username = ndb.StringProperty(required = True)
        list = ndb.StringProperty(repeated=True)

    class friend_pending(ndb.Model):
        user_username = ndb.StringProperty(required = True)
        list = ndb.StringProperty(repeated=True)

如果两者都可行,哪个在成本和性能方面更好?

I want to make both friend_list and friend_pending to be child of Users entity. Is it possible?

是的。当您创建一个实体时,您可以使用 "parent" 参数为该实体指定一个(或多个)父级。

Google's Entity Keys 部分介绍了这口井。

示例:

#Create User entity
#This code assumes you're using GAE's built-in user's class
user = users.User("Albert.Johnson@example.com")
user.put()

#Create a friend list and set its parent to the user we create above
friend_list = Friend_List(parent=user)

#Save to datastore
friend_list.put()​

请记住,GAE 中的用户 class 是专门定义的,具有您需要确认的附加功能。请参阅文档 here

If both are possible, which are better for cost and performance?

我不能肯定地说,因为我不知道你将如何使用这些模型,但在大多数(也许是所有)情况下,你的第一种方法会更有效。

最后,Datastore 模型的正确命名约定是首字母大写。例如,您的好友列表 class 应该是 "Friend_List".