2012-04-04 29 views
2

我稱典範「客戶」在谷歌應用程序引擎的Python:在谷歌應用程序引擎,如何檢查模型是否爲空?

class Customer(db.Model): 
    name = db.StringProperty() 
    age = db.IntegerProperty() 

之前,我創建Customer模型的任何實例/對象,我想檢查模式是空的(沒有物體創建了),我嘗試在Python這樣的:

customers = Customer.all() 
for customer in customers: 
    if customer: 
     logging.info("there is customer in Customer Model!") 
    else: 
     logging.info("The Customer Model is empty!") 
........ 

當有客戶模型沒有實例/對象,「客戶」,在上面的代碼是不是「無」,而行「爲客戶的客戶: 「總是跳出來(意味着」客戶「中什麼都沒有?),有什麼想法?另外,我可以在Django模板中檢查這個嗎? 預先感謝您。

+0

請界定 「空」 模型 – 2012-04-04 12:06:33

回答

3

你可以使用count()

customers = Customer.all() 
if customers.count(1): 
    # do something 
+0

感謝aschmid00,它的工作原理。當Customer模型中沒有可用於檢查模型是否爲空的實例時,customers.count()返回int 0(False)。 – cnherald 2012-04-04 13:20:57

+1

@cnherald使用計數(1)保存一些週期 – 2012-04-04 13:24:26

+0

嗨謝伊,如何使用count(1)而不是count(),有什麼區別? – cnherald 2012-04-04 13:34:01

1

- 編輯:請勿使用此代碼 -
此代碼是比使用計數慢(1),我要離開這個不好的參考。


customers = Customer.all().get() 
if customer: 
    logging.info("there is customer in Customer Model!") 
else: 
    logging.info("The Customer Model is empty!") 
+0

不錯,它也適用。你能解釋一下Customer.all()。get()返回什麼?謝謝。 – cnherald 2012-04-04 13:43:52

+1

@cnherald它執行查詢並返回第一個結果 – 2012-04-04 13:56:06

+0

感謝Shay再次發表您的評論。 – cnherald 2012-04-04 14:26:32