2017-06-01 60 views
1

我在數據存儲的用戶模型包含一些屬性:App Engine的查詢用戶

enter image description here

我需要查詢所有用戶的company屬性過濾。

所以,我通常會做什麼,我這樣做:

from webapp2_extras.appengine.auth.models import User 

employees = User.query().filter(User.company == self.company_name).fetch() 

這給了我:

AttributeError: type object 'User' has no attribute 'company'

當我做:

employees = User.query().filter().fetch() 

它沒有給我錯誤並顯示所有用戶的列表。

如何按字段查詢?謝謝

回答

1

您的問題有點誤導。你問如何按字段查詢,你已經用正確的語法進行了查詢。正如傑夫奧尼爾指出的那樣,問題是您的User模型沒有company字段,因此您的按字段查詢嘗試會導致錯誤。 (Here is some ndb documentation,你一定要仔細閱讀及書籤,如果你還沒有。)有三種方法來彌補丟失的場問題:

  1. 子類User模型,傑夫顯示了他的答案。這很快且簡單,可能是您想要的最佳解決方案。
  2. 創建您自己的用戶模型,完全獨立於webapp2之一。從你的問題來看,這可能是矯枉過正的,因爲你必須編寫webapp2用戶已經爲你處理的大部分自己的認證代碼。
  3. 創建一個新模型,其中包含額外的用戶信息,並具有包含相應用戶密鑰的密鑰屬性。這將是這樣的:

    class UserProfile(ndb.Expando): 
        user_key = ndb.KeyProperty(kind='User', required=True) 
        company = ndb.StringProperty() 
        # other possibilities: profile pic? address? etc. 
    

    與這樣的疑問:

    from models.user_profile import UserProfile 
    from webapp2_extras.appengine.auth.models import User 
    from google.appengine.ext import ndb 
    
    # get the employee keys 
    employee_keys = UserProfile.query(UserProfile.company == company_name).fetch(keys_only=True) 
    
    # get the actual user objects 
    employees = ndb.get_multi(employee_keys) 
    

    什麼這個解決方案所做的就是從模型中分離您用於身份驗證的用戶模型(webapp2的的用戶)持有額外用戶信息(UserProfile)。如果您想要爲每個用戶存儲個人資料照片或其他相對較大的數據,您可能會發現此解決方案對您最適合。

注意:您可以把您的篩選條件在.query()括號把事情簡單化(我發現我很少用.filter()法):

# long way 
employees = User.query().filter(User.company == self.company_name).fetch() 

# shorter way 
employees = User.query(User.company == self.company_name).fetch() 
1

您已導入由webapp2定義的User類。此User類沒有名爲company的屬性,因此這就是爲什麼您從User.company獲得錯誤的原因。

你可能想通過繼承由webapp2的提供了一個做創建您自己的User型號:

from webapp2_extras.appengine.auth.models import User as Webapp2_User 

class User(Webapp2_User): 
    company = ndb.StringProperty() 

然後將查詢應該工作。

一個警告,我從來沒有使用webapp2_extras.appengine.auth.models所以我不知道那是什麼。

+0

感謝傑夫,這就是我要的情況下,做我沒有用更簡單的方法取得成功。在重新實施方面更簡單。 –