ndb多对多,检索其中一个关系的列表

时间:2015-01-08 10:04:11

标签: python google-app-engine google-cloud-datastore data-modeling app-engine-ndb

我有这张桌子

class ClubMembership(GCModel):
    member = ndb.KeyProperty(kind='User', required=True)
    club = ndb.KeyProperty(kind='Club', required=True)
    is_active = ndb.BooleanProperty(default=True)
    membership_type = ndb.StringProperty(choices=set(["MEMBER", "TRAINER", "OWNER"]), default="MEMBER",
                                     required=True)

然后在表格中Club我就是这个

class Club(GCModel):
    @property
    def members(self):
        return ClubMembership.query(ndb.AND(ClubMembership.club == self.key,
                                            ClubMembership.membership_type == "MEMBER",
                                            ClubMembership.is_active == True))

我真正需要的是检索User列表。我该怎么办?

获取此查询,而不是使用for循环来使用其键获取每个member

我尝试使用ndb.get_multi使用member上的投影,但它不起作用。 像这样的东西

members= ClubMembership.query(ndb.AND(ClubMembership.club == self.key,
                                            ClubMembership.membership_type == "MEMBER",
                                            ClubMembership.is_active == True),projection=['member']).fetch()
ndb.get_multi(members)

2 个答案:

答案 0 :(得分:3)

get_multi适用于键列表,您有一个ClubMembership实例列表。您需要获取每个的member密钥:

memberships = ClubMembership.query(...)
member_keys = [m.member for m in memberships]
members = ndb.get_multi(member_keys)

答案 1 :(得分:1)

您还应该考虑将会员信息存储在用户的实体中。通过这种方式,您可以在单个查询中获得所有用户,这要快得多。

class Membership(ndb.Model):
  club = ndb.KeyProperty(kind='Club', required=True)
  is_active = ndb.BooleanProperty(default=True)
  membership_type = ndb.StringProperty(
    choices=set(["MEMBER", "TRAINER", "OWNER"]), default="MEMBER", required=True)

class User(ndb.Model):
  memberships = ndb.StructuredProperty(Membership, repeated=True)

class Club(ndb.Model):
  @property
  def members(self):
    membership = Membership(
      User.memberships.club == self.key,
      User.memberships.membership_type == 'MEMBER',
      User.memberships.is_active == True)
    return User.query(User.memberships == membership)