my current App uses a db.ListProperty(db.Key) for a many to many relation for a friendlist.
We have the following scheme:
# previous models
class User(db.Model):
name = db.StringProperty()
nickname = db.StringProperty()
join_date = db.DateProperty(auto_now_add=True)
party = db.ReferenceProperty(PartyEntry, collection_name='participants')
def by_name(self, string):
return self.gql("WHERE name = :name", name=string).get()
def key_by_name(self, string):
return self.by_name(string).key()
class FriendList(db.Model):
owner = db.ReferenceProperty(User)
friends = db.ListProperty(db.Key)
And a handler that fetches a users friendlist, processes it and displays it:
class Profile_FriendList(WebBase):
def get(self):
user = self._auth()
if user:
usr_key = User().key_by_name(user.nickname())
friend_list = friend_lists = FriendList.all().filter('owner', usr_key).fetch(10)
self.renderskeleton( { 'friendlist': friend_list } ,'friends.html')
I populated a test friendlist with two db.Key() list entries in FriendList.friends.
The s.c. SDK Console (>Interactive Datastorageviewer) diplays me those items:
key1,key2
But if I call this entity FriendList by its key and
print frlst.friends
output: []
Same problem in the handler.
I get no data I can work with.
BUT the data exist.
Fixed: FriendList problem, the called friendlist object wasn’t a query it simply was a new FriendList() object.
Updated code.
Fixed: Complete question solved
usr_key = User().key_by_name(user.nickname())
logging.info(user.nickname())
logging.info(usr_key)
friend_list = FriendList().all().filter("owner", usr_key).fetch(20)
logging.info(friend_list)
logging.info(friend_list[0].friends)
friends = User.get(friend_list[0].friends)
logging.info(friends)
self.renderskeleton( { 'friends': friends } , 'friends.html')
I selected a list of GqlQuery results instead of the “one” I want, what I had to do from there was simply putting the friends’ key list into an User.get() and voilà I had all necessary data.
friend_list = FriendList(owner=usr_key)is not a query, it is creating a new instance of FriendList.You want:
friend_lists = FriendList.all().filter('owner', usr_key).fetch(10).Other comments:
The two methods on User your using for queries should really be class methods:
Have you considered using the user’s id with
get_by_key_name()? It would be faster than a query.Also use the user’s id as the key_name for the friend-list, then instead of a query you can do
friend_list = FriendList.get_by_key_name(str(user.user_id())). You’ll need a way to handle case where one FriendList is not enough, but those will probably be rare — and it is not that difficult to solve (add a sequence number to the key_name and store a (non-indexed) count of the sequences on the User kind, then you can easily generate the key_names).