如果我有一个带引用属性的对象,那么在引用属性上调用.key()或.key()。id()方法会导致从数据存储中检索它吗?或者我可以从没有触发请求的那些人那里获得价值吗?
class MyObject(db.Model):
reference = db.ReferenceProperty()
myObj = MyObject( reference = myOtherObject )
myObj.put()
# Will this retrieve the key without doing a get for the object?
temp1 = myObj.reference.key()
# What about this?
temp2 = myObj.reference.key().id()
答案 0 :(得分:10)
从模型实例访问该属性将取消引用它(它将被获取):
# This will retrieve the key after doing a get for the object.
temp1 = myObj.reference.key()
要获取密钥而不取消引用,请使用:
# This will retrieve the key without doing a get for the object.
temp1 = MyObject.reference.get_value_for_datastore(myObj)
# Then you get the id...
temp2 = temp1.id()
答案 1 :(得分:0)
是。访问始终触发ReferenceProperty子查询。
使用ReferenceProperty时,我通常会再存储两个属性。保存参考模型时,我还存储代表键的字符串和id的int。
class MyObject(db.Model):
reference = db.ReferenceProperty()
referenceStrKey = db.StringProperty()
referenceId = db.IntProperty()
最近我只将密钥存储为字符串,然后将广告存储到属性:
class MyObject(db.Model):
referenceStrKey = db.StringProperty()
@property
def reference(self):
return RefModel.get(db.Key(self.referenceStrKey))
@property
def referenceId(self):
return db.Key(self.referenceStrKey).id()