1

I have got this query in Peewee:

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

How to check if it returns data?

I tried:

if c.count() > 0:

if len(c) > 0

It does not work for me

This is full code:

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()
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Gundama
  • 33
  • 1
  • 5

2 Answers2

0

Your code is all kinds of wrong.

First of all, the 2nd call to "get()" is not necessary here:

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

Second of all, you are returning an assignment (?) which makes no sense. Change to:

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

If the product exists, it will be returned. If not, a DoesNotExist exception will be raised, making it unnecessary to call "count()" anywhere.

To make the code work even if the product is not found:

try:
    return Products.get(Products.sku == article)
except Products.DoesNotExist:
    # Product was not found.
    return
coleifer
  • 24,887
  • 6
  • 60
  • 75
-1

You can use count().

Here is a working code:

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
Yasushi Shoji
  • 4,028
  • 1
  • 26
  • 47