简体   繁体   中英

In google app engine, how to check if a model is empty or not?

I have a model called "Customer" in google app engine with python:

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

before I create any instance/object of the Customer model, I would like to check if the model is empty(no object has been created), I tried something in Python like:

 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!")
 ........

when there is no instance/object in Customer model, "customers" in above snippet is not "None", while the line "for customer in customers:" always jumps out(means there is nothing in "customers"?), any idea? in addition, can I check this in Django template? thank you in advance.

you could use count()

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

-- EDIT: DON'T USE THIS CODE --
This code is slower than using count(1), I'm leaving this a bad reference.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM