2013-02-24 98 views
1

我正在使用下面的代碼來獲取行中的所有值。獲取行上的所有字段值

from google.appengine.ext import db 
from python_lib.models import Field 

field = Field.all()[0] 
names = Field.properties() 

for key in names: 
    print field.get(key) 

但它給下面的錯誤,

BadKeyError: Invalid string key name. 
+1

您是否嘗試過打印''names''和''field.keys()'' - 因爲可能錯誤是有效的。 – sotapme 2013-02-24 17:14:10

+0

@sotapme名稱打印正確。使用Get – Saqib 2013-02-25 04:23:59

回答

2

你混淆了太多不同的API在此代碼。

for key in names: 
    print field.get(key) 

你的get()的調用是無效的,因爲你實際上是試圖調用類的方法來從數據存儲實體 - 看到的文檔這種方法https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_get

從現場的情況下獲得通過名稱的屬性(你的對象),你應該使用getattr

for key in names: 
    print getattr(field,key) 

或全部交替使用屬性的對象,被返回的get_value_for_datastore(model_instance)從properties()調用以及屬性的名稱。

0

這是你想要的嗎?

代碼:

from google.appengine.ext import db 

class Field(db.Model): 
    author = db.StringProperty() 
    content = db.StringProperty(multiline=True) 
    date = db.DateTimeProperty(auto_now_add=True) 

a = Field(author="me") 
a.put() 

編輯:

field = Field.all() 
for f in field: 
    print f.author 
    print f.content 


props = Field.properties() 

print props 
for vals in props: 
    print vals 

輸出:

<__main__.Field object at 0xb8c9e4c> 
{'content': <google.appengine.ext.db.StringProperty object at 0xb7c0aec>, 'date':  <google.appengine.ext.db.DateTimeProperty object at 0xb7c06cc>, 'author':  <google.appengine.ext.db.StringProperty object at 0xb7c0f6c>} 
content 
date 
author 
+0

時,使用它們打印字段值時會出現問題這將只打印名稱。我想從字段對象中獲取值。 – Saqib 2013-02-25 04:25:04

+0

屬性是字段名等值這些值來自查詢 - 也看看ndb https://developers.google.com/appengine/docs/python/ndb/ – 2013-02-25 07:56:04