Google App Engine - Multiple child/parent

≯℡__Kan透↙ 提交于 2019-12-25 04:15:38

问题


I want to make friend system that have db model like this:

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 is model for friend that not yet accepted. While friend_list is model for friend that are accepted.

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

Here's the second approach if it is not possible:

    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)

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


回答1:


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

Yes. When you create an entity, you can use the "parent" parameter to designate a parent (or parents) for the entity.

Google's Entity Keys section covers this well.

Example:

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

Keep in mind that the Users class in GAE is specially defined and has additional functions that you need to acknowledge. See the documentation here.

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

I can't say for sure because I don't know exactly how you will be using these models, but in most(maybe all) cases your first approach would be more efficient.

Lastly, the correct naming convention for Datastore models is to capitalize the first letter. For example, your friend list class should be "Friend_List".



来源:https://stackoverflow.com/questions/32194505/google-app-engine-multiple-child-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!