1

我相信这对 Python 来说很琐碎但相当新。

我正在尝试使用谷歌应用引擎创建一个模型。

基本上从 E/R 的角度来看,我有 2 个带有连接表的对象(连接表捕获连接的时间点)像这样

Person      | Idea     | Person_Idea
-------------------------------
person.key   idea.key    person.key
                         idea.key
                         date_of_idea

我的 Python 代码看起来像

class Person (db.Model):
  #some properties here....

class Idea(db.Model):
  #some properties here....

class IdeaCreated(db.Model):
  person= db.ReferenceProperty(Person)
  idea= db.ReferenceProperty(Idea)
  created = db.DateTimeProperty(auto_now_add = True)

我想要做的是有一种方便的方式来获取一个人的所有想法(绕过想法创建的对象)——有时我会直接需要想法列表。

我能想到的唯一方法是在 User 类上添加以下方法

def allIdeas(self):
  ideas = []
  for ideacreated in self.ideacreated_set:
     ideas.append(ideacreated.idea)
  return ideas

这是唯一的方法吗?我有更好的方法吗?

还假设我可以有一个 GQL 并绕过对ideaCreated 实例进行水合(不确定确切的语法),但将 GQL 查询对我来说是错误的。

4

1 回答 1

4

您应该将该人用作该想法的祖先/父母。

idea = Idea(parent=some_person, other_field=field_value).put()

然后您可以查询 some_person 是祖先的所有想法

persons_ideas = Idea.all().ancestor(some_person_key).fetch(1000)

祖先键将包含在Idea实体键中,一旦创建实体,您将无法更改该祖先。

我强烈建议您使用ndb而不是db https://developers.google.com/appengine/docs/python/ndb/

ndb你甚至可以使用StructuredPropertyLocalStructuredProperty https://developers.google.com/appengine/docs/python/ndb/properties#structured

编辑:
如果您需要多对多关系,请查看 ListProperties 并将 Persons 键存储在该属性中。然后您可以在该属性中使用该键查询所有想法。

class Idea(db.Model):
    person = db.StringListProperty()

idea = Idea(person = [str(person.key())], ....).put()

将另一个人添加到想法中

idea.person.append(str(another_person.key())).put()

ideas = Idea.filter(person=str(person.key())).fetch(1000)

查看https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#ListProperty

于 2012-12-13T14:21:01.597 回答