【问题标题】:In google app engine, how to check if a model is empty or not?在谷歌应用引擎中,如何检查模型是否为空?
【发布时间】:2012-04-04 10:56:41
【问题描述】:

我在使用 python 的谷歌应用引擎中有一个名为“客户”的模型:

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

在我创建客户模型的任何实例/对象之前,我想检查模型是否为空(没有创建对象),我在 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!")
 ........

当Customer模型中没有实例/对象时,上面sn-p中的“customers”不是“None”,而“for customer in customers:”这行总是跳出来(意思是“customers”里面什么都没有?), 任何想法?另外,我可以在 Django 模板中检查这个吗? 提前谢谢你。

【问题讨论】:

    标签: python django google-app-engine


    【解决方案1】:

    你可以使用 count()

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

    【讨论】:

    • 感谢 schmid00,它可以工作。当 Customer 模型中没有可用于检查模型是否为空的实例时,customers.count() 返回 int 0 (False)。
    • @cnherald 使用 count(1) 来节省一些周期
    • 嗨,Shay,如何使用 count(1) 而不是 count(),有什么区别吗?
    • @cnherald 使用 count(1)(将 1 作为参数传递)执行计数查询,但如果您不这样做并且数据存储区中有很多实体,则会在达到 1 时返回它将持续到 1000。
    【解决方案2】:

    -- 编辑:不要使用此代码 --
    这段代码比使用 count(1) 慢,我把它作为一个不好的参考。


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

    【讨论】:

    • 不错,它也可以。你能解释一下 Customer.all().get() 返回什么吗?谢谢。
    • @cnherald 它执行查询并返回第一个结果
    • 这会比.count(1)慢。
    • @NickJohnson 谢谢,有道理,因为它需要返回一个实体,而 count(1) 返回一个 int。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2012-08-18
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多