gpt4 book ai didi

具有 ReferenceProperty 和连接表的 Python 模型

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:00 25 4
gpt4 key购买 nike

我认为这对 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 类上添加 follow 方法

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

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

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

最佳答案

你应该把这个人当作这个想法的祖先/ parent 。

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

关于具有 ReferenceProperty 和连接表的 Python 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13860524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com