hd_riqi hd_riqi - 3 months ago 16
Python Question

Google App Engine - Multiple child/parent

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?

Answer

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".

Comments