需要帮助了解ReferenceProperty吗

2024-03-28 23:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两门课:

class A(db.Model):

class B(db.Model):
    a_reference = ReferenceProperty(A)

我现在可以执行以下操作:

^{pr2}$

documentation声明了以下两件事:

The ReferenceProperty value can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way.

后来还说:

An application can explicitly db.get() the value of a ReferenceProperty (which is a Key) to test whether the referenced entity exists.

那这是什么意思?该值是key,但它可以用于模型实例吗?在

如果我这样做:

a2 = b.a_reference

a2的类型是A,而不是key。这是否意味着变量a_reference在删除该实例之前其行为将类似于模型实例,然后它将返回一个键(指向不存在的实例)?在


Tags: andthe实例instancedbmodelvalueit
1条回答
网友
1楼 · 发布于 2024-03-28 23:18:22

ReferenceProperty将始终尝试返回存储的键指向的类的实例。如果被引用的对象已经被删除,我相信你不会得到任何回复。From the docs

obj1 = obj2.reference

if not obj1:
    # Referenced entity was deleted.

如果要获取最初存储的密钥,可以使用get_value_for_datastore

^{pr2}$

相关问题 更多 >