-1

如何在我的代碼中設置entity的密鑰。在Google App Engine中設置NDB中的實體密鑰

例子,我有一個用戶類

class User(ndb.Model) 
    email 

我希望能夠使用電子郵件財產

my_user = User(email='[email protected]')

上面的語句設置電子郵件屬性設置email屬性和查詢,但谷歌應用程序引擎生成自己的密鑰。

我可以使用該密鑰

設置使用用戶(key=' [email protected]')

如果我能在實體設置的鍵屬性的關鍵,我該如何查詢一個實體

這是否工作 User.query(key='[email protected]')。獲得()

我知道我可以使用email作爲一個屬性查詢,但不幸的是我不能這樣做,在上下文一個transaction

這就是我要求如何通過鍵獲取(),設置()的原因。

此外,當我通過性能結束了查詢,我需要創建性能指標,我知道會是唯一的

回答

1

是的,但它不是my_user = User(key='[email protected]'),它是:

my_user = User(id='[email protected]') 
my_user_key = my_user.put() 

現在, my_user_key是關鍵,這樣你就可以得到它:

the_user_entity = my_user_key.get() 

或者更高版本,可以通過構建一個重點得到它:

my_user_key = ndb.Key(User, id='[email protected]') 
the_user_entity = my_user_key.get() 

或直接由:

User.get_by_id('[email protected]') 
+0

謝謝! 如何通過電子郵件查詢用戶'[email protected]' User.query(id='[email protected]')。get()或User.get_by_id('[email protected]' )> App引擎是否自動擁有'id'屬性的索引,或者是否應該在index.yaml中爲'id'屬性包含一個索引 – user462455

+0

是的,密鑰是索引在每個實體上的,否則它將不可查詢。我的答案中的任何一種方法都可以工作(使用'get()',或者使用get_by_id()'查詢是不必要的昂貴。 – GAEfan

+0

Thanks!如何訪問ndb.Model對象上的id屬性。我有一個用戶對象,做user.id給出了一個錯誤,說用戶(ndb.Model)沒有屬性'ID' – user462455

相關問題