【问题标题】:How to check (count) are returned data?如何检查(计数)是否返回数据?
【发布时间】:2018-07-26 12:19:01
【问题描述】:

我在 Peewee 中得到了这个查询:

return c = Products.get(Products.sku == article).get()

如何判断是否返回数据?

我试过了:

if c.count() > 0:

if len(c) > 0

它不适合我

这是完整的代码:

try:
    r = self.isProductExist(row['sku'])

    ## if (r.count() == 0):

except peewee.DoesNotExist:

   # Insert product


    def isProductExist(self, article):
      return Products.get(Products.sku == article).get()

【问题讨论】:

  • return c = Products.get(Products.sku == article).get() 不是有效代码。只需执行c = Products.get(Products.sku == article).get()。你能详细说明你是怎么知道它不起作用的吗?它会给你一个错误吗?
  • 我把这个查询放在试试:except peewee.DoesNotExist:
  • 用代码更新你的问题
  • @Gundama 对不起,我想我不明白你的问题。如果您提供更多代码,我相信这里有人可以提供帮助。
  • 完成,查看问题

标签: python peewee flask-peewee


【解决方案1】:

您可以使用count()

这是一个工作代码:

import peewee
from peewee import *

db = SqliteDatabase('/tmp/a.db')

class Products(Model):
    sku = CharField()
    class Meta:
        database = db

db.connect()
db.drop_tables(models=[Products], safe=True)
db.create_tables([Products])


count = Products.select().count()
print(count) #=> 0
if not count:
    Products.create(sku="abc")

print(Products.select().count()) #=> 1

print(peewee.__version__) #=> 3.0.18

【讨论】:

  • count() 已经存在很长时间了,它并不特定于 3.x。
  • @coleifer 谢谢,已修复。你还发现了什么错误?
  • 不,看起来不错。
【解决方案2】:

你的代码有各种各样的错误。

首先,这里不需要第二次调用“get()”:

return c = Products.get(Products.sku == article).get()

其次,您正在返回一个没有意义的赋值 (?)。改为:

 return Products.get(Products.sku == article)

如果产品存在,它将被退回。否则,将引发 DoesNotExist 异常,因此无需在任何地方调用“count()”。

即使没有找到产品也可以使代码工作:

try:
    return Products.get(Products.sku == article)
except Products.DoesNotExist:
    # Product was not found.
    return

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 2019-06-20
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多