How to find if a friendship exist?

34 views
Skip to first unread message

Emmanuel Mayssat

unread,
Nov 20, 2012, 1:45:33 PM11/20/12
to google-a...@googlegroups.com
I have a model as follow

class User(db.Model):
       name = db.StringProperty(required=True)

class Friendship(db.Model):
       user1 = db.ReferenceProperty(required=True, collection_name="user1_set")
       user2 = db.ReferenceProperty(required=True, collection_name="user2_set")

I can create users and friendship relationship between them.
Now the question is:
How can I find if to people are already friends?

Jesse

unread,
Nov 20, 2012, 3:48:25 PM11/20/12
to google-a...@googlegroups.com
Don't model it like this :).

Seriously, do something like this:

class FriendShip(db.Model):
    account_id = db.IntegerProperty()  # Sure use refprop if you want, waste of space IMHO

Then create it like this:

friendship = FiendShip(parent=db.Key.from_path('User', USER_1_ID, 'Friend', USER_2_ID), account_id=USER_2_ID)
# Then make another one under the other guy:
friendship_sym = FiendShip(parent=db.Key.from_path('User', USER_2_ID, 'Friend', USER_1_ID), account_id=USER_1_ID)

db.put([friendship, friendship_sym])

That does this do?

 * Testing for friendship: db.get(db.Key.from_path('User', USER_1_ID, 'Friend', USER_2_ID)) -- if not None they are friends.
 * Friends of user one? FriendShip.all(ancestor=db.Key.from_path('User', USER_1_ID))  # Note--this is always consistent! Woohoo!
 * Everyone that is friends with user 2? FriendShip.all().filter('account_id', USER_2_ID) # Not always consistent, but pretty close :)

-Jesse

Jesse

unread,
Nov 20, 2012, 3:49:07 PM11/20/12
to google-a...@googlegroups.com
Typo: FriendShip(key= not FriendShip(parent=
Reply all
Reply to author
Forward
0 new messages