views:

50

answers:

1

How to make a light query for a many to many relationship?

Users has many Lists

the ListUser is the model that links them

Currently I'm doing like this but there are a lot of get queries to get all this data.

lists = []
for list in user.lists:
    lists.append(list.list)

Now I got this:

list_users = user.lists.fetch(1000)
# problem is here: "list.list" will retrive data from database, but I just want that list's key, how to do?
list_keys = [list.list for list in list_users]
lists = List.get_by_key_name(list_keys)
A: 

You should use get_value_for_datastore.

list_keys = [ListUser.list.get_value_for_datastore(list_user)
              for list_user in list_users]
lists = db.get(list_keys)

If you have not already, you might want to take a look at some of the 'mastering the datastore' articles. Specifically the one on modeling relationships. Perhaps you can accomplish what you need using a list of List keys instead, maybe it will save you a query.

Robert Kluin
This can work too, right?list_users = user.lists.fetch(1000);list_keys = [list._list for list in list_users];lists = List.get(list_keys);
Totty
Yes, that also works. With the current implementation of ReferenceProperty the two methods are effectively identical. However, get_value_for_datastore is publicly documented, so you code is less likely to be broken by any internal changes.
Robert Kluin
So using "get_value_for_datastore" is better, right?
Totty
And is any way to only request the list's key? When I query for user.lists.fetch(1000) so it would be mych lighter
Totty
You could potentially make it 'lighter' by storing a list of db.Keys for each user. That would allow you fetch a user then directly fetch their list of groups from the list of Keys. It would also allow you to easily find all users who are in a particular group with an easy query.
Robert Kluin
And yes, I generally prefer get_value_for_datastore since it is a 'public' api function.
Robert Kluin
@Robert Kluin: thanks, but as each user can have a large number of lists, shared and each has metadata is better with the linkage model.
Totty