1

My model is like this

  • Club
  • User
  • Course
    • reference to club (key)
  • Session
    • reference to Course (key)
  • ClubMembership
    • reference to club (key)
    • reference to user (key)
  • CourseSubscription
    • reference to course (key)
    • reference to user (key)

Now, i want to have all the courses i'm subscribed to, having as input a club and a user

what i did is:

courses = Courses(Courses.club == club.key).fetch(keys_only=True)
real_list = []
for course in courses:
   if CourseSubscription.get_by_id(user, course):
       real_list.append(course)
sessions = Session.query(Session.course.IN(real_list),Session.start_date >= start_date).fetch()

for CourseSubscription i used this https://stackoverflow.com/a/26746542/1257185, this is why i can do the if (yet it's expensive)

is there a better way to do it? at least less expensive. i was thinking of gql, but then i've a list of IN to do. probably smt like: select key from courseSubscription, where course.club = {clubid} and user = {user} then a ndb_get_multi to load the query results? is this possible somehow?

Community
  • 1
  • 1
EsseTi
  • 4,079
  • 5
  • 36
  • 63

1 Answers1

1

The for loop makes a number of requests and you can combine them into a single request.

If your CourseSubscription is the same as the CourseInscription in your SO link above, then you could get a list of subscription keys and make a single get_multi() call to get all of the subscriptions:

subscription_keys = [ndb.Key(CourseSubscription, CourseSubscription.build_id(user, course))
                     for course in courses]
real_list = ndb.get_multi(subscription_keys)

If the key does not exist, then that subscription will be None. You will have to filter those out.

Brent Washburne
  • 12,904
  • 4
  • 60
  • 82
  • didn't test but seems very good indeed. the `None` will be in `real_list`, correct? if so what's the best way to remove `None` from a list? i guess probably it's this http://stackoverflow.com/a/16096769/1257185 – EsseTi Jan 15 '15 at 16:46
  • Yes, that's probably the best way: `real_list = [s for s in ndb.get_multi(subscription_keys) if s is not None]` – Brent Washburne Jan 15 '15 at 18:56